How to manually create a PDF page from an Image?

Question:
I want to create a PDF page from an image, but not using ToPDF(), nor StreamingPDFConversion(), how do I do that?

Answer:
The following code creates a PDF page entirely filled by source image, and sized to reflect image DPI.

using (PDFDoc doc = new PDFDoc())
using (ElementBuilder bld = new ElementBuilder())
using (ElementWriter writer = new ElementWriter())
{
	Image img = Image.Create(doc, input_path + "peppers.jpg");
	int imgW = img.GetImageWidth();
	int imgH = img.GetImageHeight();
	int pdfDPI = 72; // default PDF DPI
	int imgDPI = 96; // assume image DPI is 96 (could use 3rd party image tool to see if image includes DPI metadata
	double pdfUnitsW = imgW / imgDPI * pdfDPI;
	double pdfUnitsH = imgH / imgDPI * pdfDPI;
	Page page = doc.PageCreate(new Rect(0,0,pdfUnitsW,pdfUnitsH));
	writer.Begin(page);
	Element element = bld.CreateImage(img, 0, 0, pdfUnitsW, pdfUnitsH);
	writer.WritePlacedElement(element);
	writer.End();
	doc.PagePushBack(page);
	doc.Save(output_path + "addimage_00.pdf", SDFDoc.SaveOptions.e_linearized);
}

Note: just like how this sample doesn’t check image metadata for DPI, it also doesn’t check any possible rotation metadata. If that is a possibility you would have to use a 3rd party image library to get that data and apply (using Matrix2D class and using CreateImage() overload to apply rotation.

1 Like