Project

General

Profile

Feature #6802 » test_20181209a_pdfimage.C

Bruce Toll, 12/11/2018 11:08 PM

 
#include <fstream>
#include <Wt/WGlobal.h>
#include <Wt/WPainter.h>
#include <Wt/WPdfImage.h>

void HPDF_STDCALL 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);
}

int main(int argc, char **argv)
{
static const double MARGIN = 100.0;
static const double LINE_HEIGHT = 107.0;

HPDF_Doc pdf = HPDF_New(error_handler, 0);
if (!pdf)
throw std::runtime_error("Could not create libharu document.");

HPDF_SetCompressionMode(pdf, HPDF_COMP_ALL);
HPDF_UseUTFEncodings(pdf);

HPDF_Page page = HPDF_AddPage(pdf);

auto pageWidth = Wt::WLength("8in").toPixels();
auto pageHeight = Wt::WLength("11in").toPixels();

HPDF_Page_SetWidth(page, pageWidth);
HPDF_Page_SetHeight(page, pageHeight);
HPDF_Page_GSave(page);

Wt::WPdfImage pdfImage(pdf, page, 0, 0, pageWidth, pageHeight);
Wt::WPainter p(&pdfImage);
// std::cerr << "p.device()->width().toPixels()" << p.device()->width().toPixels() << std::endl;
// std::cerr << "p.device()->height().toPixels()" << p.device()->height().toPixels() << std::endl;

Wt::WPointF tl(0 + MARGIN, 0 + MARGIN);
Wt::WPointF br(p.device()->width().toPixels() - MARGIN,
p.device()->height().toPixels() - MARGIN);
Wt::WRectF rect(tl, br);

int lineCount = rect.height() / LINE_HEIGHT;
std::vector<Wt::WRectF> lines;
for (int i = 0; i < lineCount; ++i) {
lines.push_back(Wt::WRectF(rect.left(), rect.top() + i * LINE_HEIGHT, rect.width(), LINE_HEIGHT));
}

p.drawRect(rect);
Wt::WFont font = p.font();
font.setWeight(Wt::FontWeight::Bold);
int fontSize = 12;

p.setBrush(Wt::WBrush(Wt::WColor(255, 0, 0)));
for (int i = 0; i < lineCount; ++i) {
Wt::WColor color(0, 0, 255, 255 - (30 * i));
auto pen = Wt::WPen(color);
pen.setWidth(10);
pen.setJoinStyle(Wt::PenJoinStyle::Miter);
p.setPen(pen);
++fontSize;
font.setSize(fontSize);
p.setFont(font);
p.drawRect(lines[i]);
p.drawText(lines[i], Wt::AlignmentFlag::Center | Wt::AlignmentFlag::Middle, "This is a test");
p.drawLine(lines[i].left(), lines[i].top() + 0.5 * lines[i].height(), lines[i].right(), lines[i].top() + 0.5 * lines[i].height());
}

std::ofstream f("example.pdf", std::ios::out | std::ios::binary);
pdfImage.write(f);
HPDF_Page_GSave(page);
HPDF_Page_GSave(page);
}
(8-8/8)