本来想使用mupdf库实现pdf转为png图片,但是折腾了很久,最新版本不支持vs2013,就是使用高版本vs编译,也没有编译成功,于是换成PDFium实现这个功能,vs采用2013,以下是转换图片的代码:
// TestPdf2Img.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "fpdfdoc.h"
#include "fpdftext.h"
#include "fpdfedit.h"
#include <string>
using namespace std;
#include <stdio.h>
void WriteBmp(const char* pdf_name, int num, const void* buffer,
int stride, int width, int height) {
if (stride < 0 || width < 0 || height < 0)
return;
if (height > 0 && width > INT_MAX / height)
return;
int out_len = stride * height;
if (out_len > INT_MAX / 3)
return;
char filename[256];
sprintf(filename, "%s.%d.bmp", pdf_name, num);
FILE* fp = fopen(filename, "wb");
if (!fp)
return;
BITMAPINFO bmi = { 0 };
bmi.bmiHeader.biSize = sizeof(bmi) - sizeof(RGBQUAD);
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -height; // top-down image
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biSizeImage = 0;
BITMAPFILEHEADER file_header = { 0 };
file_header.bfType = 0x4d42;
file_header.bfSize = sizeof(file_header) + bmi.bmiHeader.biSize + out_len;
file_header.bfOffBits = file_header.bfSize - out_len;
fwrite(&file_header, sizeof(file_header), 1, fp);
fwrite(&bmi, bmi.bmiHeader.biSize, 1, fp);
fwrite(buffer, out_len, 1, fp);
fclose(fp);
}
void pdf2cimage(char *file_path, int image_Sharpness = 1)
{
FPDF_InitLibrary(NULL);
//读取pdf文件
FPDF_DOCUMENT pdf_doc = FPDF_LoadDocument(file_path, NULL);
if (pdf_doc == NULL)
{
printf("open file failed.");
return;
}
//读取pdf页数
int pageCount = FPDF_GetPageCount(pdf_doc);
if (pageCount <= 0)
{
FPDF_CloseDocument(pdf_doc);
return;
}
for (int npage = 0; npage < pageCount; npage++)
{
FPDF_PAGE pdf_page = FPDF_LoadPage(pdf_doc, npage);
FPDF_TEXTPAGE text_page = FPDFText_LoadPage(pdf_page);
int page_w = static_cast<int>(FPDF_GetPageWidth(pdf_page));
int page_h = static_cast<int>(FPDF_GetPageHeight(pdf_page));
FPDF_BITMAP bit;
bit = FPDFBitmap_Create(page_w, page_h, 0);;
FPDFBitmap_FillRect(bit, 0, 0, page_w, page_h, 0xFFFFFFFF);
FPDF_RenderPageBitmap(bit, pdf_page, 0, 0, page_w, page_h, 0, 0);
const char* buffer = reinterpret_cast<const char*>(FPDFBitmap_GetBuffer(bit));
const int stride = FPDFBitmap_GetStride(bit);
WriteBmp("xx", npage, buffer,stride, page_w, page_h);
FPDFBitmap_Destroy(bit);
FPDFText_ClosePage(text_page);
FPDF_ClosePage(pdf_page);
}
//关闭文件
FPDF_CloseDocument(pdf_doc);
}
int _tmain(int argc, _TCHAR* argv[])
{
pdf2cimage("1.pdf");
return 0;
}
所依赖的PDFium头文件与lib静态库可以在本人资源里面下载: