How to do PDF to TIFF in memory?

Question:
I want to convert a PDF page to TIFF, but in memory, with no disk access. How can I do that?

Answer:
You can do that using the PDFDraw.Export(Page, Filter, String) API. Below is .NET 5+ example, though writing to disk for demo purposes.

Note: This only does single page TIFF. If you want to generate a multi-page TIFF you need to use Convert.ToTiff which does write to disk.

using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) 
{
	// for demo purpose, writing to disk
	var fs = new System.IO.FileStream(output_path + "output.tiff", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);

	int bufSz = 64 * 1024; // 64 KiB
	Page page = doc.GetPage(1);
	var memoryFilter = new MemoryFilter(bufSz, false); // false == sink.
	draw.Export(page, memoryFilter, "TIFF");
	memoryFilter.SetAsInputFilter(); // switch MemoryFilter from Sink to Source
	var filterReader = new FilterReader(memoryFilter); // connect reader
	byte[] buf = new byte[bufSz]; // now read data as we convert
	int bytesRead = filterReader.Read(buf);
	while(bytesRead > 0) {
		fs.Write(buf, 0, bytesRead);
		bytesRead = filterReader.Read(buf);
	}
}
1 Like