Created
October 17, 2012 12:02
-
-
Save pdfcrowd/3905177 to your computer and use it in GitHub Desktop.
A simple C app that creates PDF from a local HTML file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* compile with: $ gcc pdfcrowd.c -lcurl -o pdfcrowd */ | |
#include <curl/curl.h> | |
/* | |
* return values: | |
* 0 success | |
* 1 curl fatal error | |
* 2 curl error | |
* >399 API error (HTTP status code) | |
*/ | |
long file_to_pdf(char const* fname, FILE* outfp, | |
char const* username, char const* apikey) { | |
long status_code = 0; | |
CURLcode res; | |
struct curl_httppost* post = NULL; | |
struct curl_httppost* last = NULL; | |
char errbuffer[1024]; | |
int eread = 0; | |
CURL *curl = curl_easy_init(); | |
if (!curl) { | |
fprintf(stderr, "curl_easy_init() failed\n"); | |
return 1; | |
} | |
curl_formadd(&post, | |
&last, | |
CURLFORM_COPYNAME,"username", | |
CURLFORM_COPYCONTENTS, username, | |
CURLFORM_END); | |
curl_formadd(&post, | |
&last, | |
CURLFORM_COPYNAME,"key", | |
CURLFORM_COPYCONTENTS, apikey, | |
CURLFORM_END); | |
curl_formadd(&post, | |
&last, | |
CURLFORM_COPYNAME, "src", | |
CURLFORM_FILECONTENT, fname, | |
CURLFORM_END); | |
curl_easy_setopt(curl, CURLOPT_URL, "http://pdfcrowd.com/api/pdf/convert/html/"); | |
curl_easy_setopt(curl, CURLOPT_HTTPPOST, post); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfp); | |
res = curl_easy_perform(curl); | |
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status_code); | |
if (res != CURLE_OK) { | |
fprintf(stderr, "curl_easy_perform() failed: %s\n", | |
curl_easy_strerror(res)); | |
status_code = 2; | |
} else if (status_code >= 400) { | |
/* assumes outfp is seekable */ | |
fseek(outfp, 0, SEEK_SET); | |
fprintf(stderr, "Pdfcrowd Error: [%d] ", status_code); | |
do { | |
eread = fread(errbuffer, 1, 1024, outfp); | |
fwrite(errbuffer, 1, eread, stderr); | |
} while (eread); | |
} else { | |
/* success */ | |
status_code = 0; | |
} | |
cleanup: | |
curl_formfree(post); | |
curl_easy_cleanup(curl); | |
return status_code; | |
} | |
int main(char argc, char **argv) { | |
long status; | |
char const* output_fname = "out.pdf"; | |
FILE* outfp = fopen(output_fname, "w+b"); | |
status = file_to_pdf("sample.html", outfp, "**username**", "**apikey**"); | |
fclose(outfp); | |
if (status) { | |
remove(output_fname); | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment