前言
遇到个需求,就是在qt客户端显示服务器上的pdf文档,文档以base64格式返回给客户端。以下是实现方法:
1、在pro文件增加以下代码:
INCLUDEPATH += $$PWD/PDFiumSDK/include/public
DEPENDPATH += $$PWD/PDFiumSDK/include/public
LIBS += -l$$PWD/PDFiumSDK/lib/x86/pdfium
2、pdf转图片
cpp
FPDF_InitLibrary();
// base64的数据要先转为二进制
QByteArray bytes = QByteArray::fromBase64(strBase64Code.toUtf8());
FPDF_DOCUMENT doc = FPDF_LoadMemDocument(bytes.data(), bytes.size(), "");
int pageCount = FPDF_GetPageCount(doc);
for (int t = 0; t < pageCount; t++)
{
FPDF_PAGE page = FPDF_LoadPage(doc, t);
int width = static_cast<int>(FPDF_GetPageWidth(page));
int height = static_cast<int>(FPDF_GetPageHeight(page));
FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0);
FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF);
FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, 0);
const char* buffer = reinterpret_cast<const char* >(FPDFBitmap_GetBuffer(bitmap));
// 数据转图片,使用不同的Format可能会有图片失真的现象,要多试几次
QImage image((uchar*)buffer, width, height, QImage::Format_RGB32);
QLabel *label = new QLabel(this);
label->setPixmap(QPixmap::fromImage(image));
label->setFixedSize(width, height);
// TODO addwidget(label);把label添加到显示控件中
FPDF_ClosePage(page);
count++;
}
FPDF_CloseDocument(doc);
FPDF_DestroyLibrary();