做网站建设今日最新新闻
MuPDF
Qt关于PDF的方法不多,很多时候在处理PDF时要借助第三方库,相关的库有Poppler,mupdf等。本文主要介绍了mupdf的下载,编译以及在windows下配合Qt使用将pdf中的一页转成png图片(Poppler编译起来比较麻烦)。
官方网址
下载地址
我下的是mupdf-1.15.0-source.tar.xz。下载完毕,解压到指定目录下。
打开platform/win32目录下的mupdf.sln进行编译,我编译的是release版本。
在release目录下生成一些静态库。
之后打开QtCreator创建一个控制台项目,将解压目录下include文件夹中的mupdf以及生成的静态库libmupdf.lib复制到工程目录下,Qt目录结构如下。
配置.pro文件,指定头文件目录以及连接的静态库。
main.cpp中pdf转图片代码如下(只是将pdf第一页转为图片)。
#include <QCoreApplication>
#include <stdio.h>
#include <stdlib.h>#include "fitz.h"int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);const char *input = "D:\\123.pdf";float zoom, rotate;int page_number, page_count;fz_context *ctx;fz_document *doc;fz_pixmap *pix;fz_matrix ctm;int x, y;page_number = 0;zoom = 100;rotate = 0;/* Create a context to hold the exception stack and various caches. */ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);if (!ctx){fprintf(stderr, "cannot create mupdf context\n");return EXIT_FAILURE;}/* Register the default file types to handle. */fz_try(ctx)fz_register_document_handlers(ctx);fz_catch(ctx){fprintf(stderr, "cannot register document handlers: %s\n", fz_caught_message(ctx));fz_drop_context(ctx);return EXIT_FAILURE;}/* Open the document. */fz_try(ctx)doc = fz_open_document(ctx, input);fz_catch(ctx){fprintf(stderr, "cannot open document: %s\n", fz_caught_message(ctx));fz_drop_context(ctx);return EXIT_FAILURE;}/* Count the number of pages. */fz_try(ctx)page_count = fz_count_pages(ctx, doc);fz_catch(ctx){fprintf(stderr, "cannot count number of pages: %s\n", fz_caught_message(ctx));fz_drop_document(ctx, doc);fz_drop_context(ctx);return EXIT_FAILURE;}if (page_number < 0 || page_number >= page_count){fprintf(stderr, "page number out of range: %d (page count %d)\n", page_number + 1, page_count);fz_drop_document(ctx, doc);fz_drop_context(ctx);return EXIT_FAILURE;}/* Compute a transformation matrix for the zoom and rotation desired. *//* The default resolution without scaling is 72 dpi. */ctm = fz_scale(zoom / 100, zoom / 100);ctm = fz_pre_rotate(ctm, rotate);/* Render page to an RGB pixmap. */fz_try(ctx)pix = fz_new_pixmap_from_page_number(ctx, doc, page_number, ctm, fz_device_rgb(ctx), 0);fz_catch(ctx){fprintf(stderr, "cannot render page: %s\n", fz_caught_message(ctx));fz_drop_document(ctx, doc);fz_drop_context(ctx);return EXIT_FAILURE;}fz_save_pixmap_as_png(ctx, pix, "D:\\temp.png");/* Clean up. */fz_drop_pixmap(ctx, pix);fz_drop_document(ctx, doc);fz_drop_context(ctx);return a.exec();
}