Introduction
I was working on a project in which I need to wrap a JPEG file into PDF format. The program needs to be done in C, and after searched on the Internet, I could not find anything that I can refer to. Most of the Open Source PDF engine is based on either Java or PHP, and a few C PDF engines are huge and will add a lot of unnecessary code to my project. I decided to write this simple JPEG to PDF wrapper. And it's the result of reverse-engineering of the simplest PDF file that contains one single JPEG file. I just want to share this API so you can grab and use it if you have a similar requirement.
Using the Code
Just give an example to demonstrate how to generate a 2 page PDF file based on 2 JPEG files. Please refer to testMain.c for details. But the idea is:
PJPEG2PDF pPDF;
int pdfByteSize, pdfOutByteSize;
unsigned char *pdfBuf;
pPDF = Jpeg2PDF_BeginDocument(8.5, 11);
if(NULL != pPDF) {
Loop For All JPEG Files {
... Prepare the current JPEG File to be inserted.
Jpeg2PDF_AddJpeg(pPDF, JPEG_IMGW, JPEG_IMGH, JPEG_BYTE_SIZE,
JPEG_DATA_POINTER, IS_COLOR_JPEG);
}
pdfByteSize = Jpeg2PDF_EndDocument(pPDF);
pdfBuf = malloc(pdfByteSize);
Jpeg2PDF_GetFinalDocumentAndCleanup(pPDF, pdfBuf, &pdfOutByteSize);
... Do something you want to the PDF file in the memory.
}
There are several places that you can fine-tune in the Jpeg2PDF.h file:
#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 */
That's it, guys. Enjoy.
History
- Updated [2008-12-19] - Added some extra code to auto scan the current folder and automatically obtain the JPEG image dimension from the JPEG file instead of using hard coded value before.
The JPEG image dimension code is borrowed from here.