Project

General

Profile

Bug #1094 » xhtml2pdf.cc

Koen Deforche, 12/13/2011 11:10 AM

 
// This may look like C code, but it's really -*- C++ -*-
/*
* Copyright (C) 2010 Emweb bvba, Kessel-Lo, Belgium.
*
* See the LICENSE file for terms of use.
*/

#include <boost/bind.hpp>

#include <iostream>
#include <fstream>

#include <Wt/Render/WPdfRenderer>
#include <hpdf.h>

using namespace Wt;

extern "C" {
HPDF_STATUS HPDF_UseUTFEncodings(HPDF_Doc pdf);
}

void error_handler(HPDF_STATUS error_no,
HPDF_STATUS detail_no,
void *user_data) {
fprintf(stderr, "libharu error: error_no=%04X, detail_no=%d\n",
(unsigned int) error_no, (int) detail_no);
}

void testOne(const std::string& file)
{
HPDF_Doc pdf = HPDF_New(error_handler, 0);

HPDF_SetCompressionMode(pdf, HPDF_COMP_ALL);

HPDF_UseUTFEncodings(pdf);

HPDF_Page page = HPDF_AddPage(pdf);

HPDF_Page_SetSize(page, HPDF_PAGE_SIZE_A4, HPDF_PAGE_PORTRAIT);

Render::WPdfRenderer renderer(pdf, page);
//renderer.addFontCollection("/Library/Fonts");

/*
* Only needed if Wt is not linked against libpango
*/
renderer.addFontCollection("/usr/share/fonts/truetype");
renderer.setMargin(2.54);
renderer.setDpi(96);
renderer.setFontScale(1);

std::ifstream f(file.c_str(), std::ios::in | std::ios::binary);

if (!f)
throw std::runtime_error(std::string("Could not read input file ") + file);

f.seekg(0, std::ios::end);
int length = f.tellg();
f.seekg(0, std::ios::beg);

boost::scoped_array<char> xhtml(new char[length + 1]);
f.read(xhtml.get(), length);
xhtml[length] = 0;

renderer.render(WString::fromUTF8(xhtml.get()), 0);

std::string pdfName = file.substr(0, file.length() - 4) + "pdf";
HPDF_SaveToFile(pdf, pdfName.c_str());
HPDF_Free(pdf);
}

int main(int argc, char **argv)
{
testOne(argv[1]);
// testOne(argv[1]);
}
(3-3/3)