最简单的 JPEG 图像内容 PDF 生成 API
关于如何根据 JPEG 文件作为页面内容生成 PDF 文件的文章

引言
我正在做一个项目,需要将 JPEG 文件封装成 PDF 格式。程序需要用 C 语言实现,并且在互联网上搜索后,我找不到可以参考的任何东西。大多数开源 PDF 引擎都是基于 Java 或 PHP 的,而少数 C PDF 引擎体积庞大,会给我的项目添加很多不必要的代码。我决定编写这个简单的 JPEG 到 PDF 封装器。它是对包含单个 JPEG 文件的最简单的 PDF 文件的逆向工程的结果。我只是想分享这个 API,以便您可以在有类似需求时获取并使用它。
Using the Code
举个例子来演示如何基于 2 个 JPEG 文件生成 2 页 PDF 文件。请参阅 testMain.c 以获取详细信息。但思路是
PJPEG2PDF pPDF;
int pdfByteSize, pdfOutByteSize;
unsigned char *pdfBuf;
pPDF = Jpeg2PDF_BeginDocument(8.5, 11);
/* pdfW, pdfH: Page Size in Inch ( 1 inch=25.4 mm ); Letter Size 8.5x11 */
if(NULL != pPDF) {
Loop For All JPEG Files {
... Prepare the current JPEG File to be inserted.
/* You'll need to know the dimension of the JPEG Image,
and the ByteSize of the JPEG Image */
Jpeg2PDF_AddJpeg(pPDF, JPEG_IMGW, JPEG_IMGH, JPEG_BYTE_SIZE,
JPEG_DATA_POINTER, IS_COLOR_JPEG);
}
/* Call this after all of the JPEG image has been inserted.
The return value is the PDF file Byte Size */
pdfByteSize = Jpeg2PDF_EndDocument(pPDF);
/* Allocate the buffer for PDF Output */
pdfBuf = malloc(pdfByteSize);
/* Output the PDF to the pdfBuf */
Jpeg2PDF_GetFinalDocumentAndCleanup(pPDF, pdfBuf, &pdfOutByteSize);
... Do something you want to the PDF file in the memory.
}
在 Jpeg2PDF.h 文件中,有几个地方可以进行微调
#define MAX_PDF_PAGES 256 /* Currently only supports less than 256 Images */
#define PDF_TOP_MARGIN (0.0 * PDF_DOT_PER_INCH) /* Currently No Top Margin */
#define PDF_LEFT_MARGIN (0.0 * PDF_DOT_PER_INCH) /* Currently No Left Margin */
就这样了,各位。请享用。
历史
- 更新 [2008-12-19] - 添加了一些额外的代码,以自动扫描当前文件夹并自动从 JPEG 文件中获取 JPEG 图像尺寸,而不是使用之前硬编码的值。
JPEG 图像尺寸代码借用自 这里。