Place JPEG photos into a PDF without recompression
View as MarkdownThis sample shows how to put JPEG photos into a PDF quickly and with little memory by storing their original compressed data in the file as is. An image loaded with CompressedImage.CreateFromFile keeps its encoded bytes, and Graphics.DrawImage writes them to the PDF without decoding and compressing them again: the photos are never held in memory as pixels, no time is spent on JPEG decoding and encoding, and there is no second JPEG quality loss. RGB and CMYK JPEG files are both kept as is. For comparison, the sample writes the same photos to a JPEG-compressed PDF once more from decoded Bitmap objects and prints how long each way takes.
Code Snippet
var photos = new[] { "Venice.jpg", "Copenhagen_CMYK.jpg" };
var stopwatch = Stopwatch.StartNew();
using (var writer = new PdfWriter("PlaceJpegWithoutRecompression.pdf"))
using (var graphics = writer.GetGraphics())
{
writer.Compression = CompressionType.Jpeg;
foreach (var photo in photos)
{
// Keeps the JPEG data as it is in the file instead of decoding it to pixels.
using (var image = CompressedImage.CreateFromFile(photo))
{
writer.AddPage(image.Width, image.Height, image.DpiX, image.DpiY);
graphics.DrawImage(image, 0, 0);
}
}
}
Console.WriteLine("CompressedImage: {0} ms", stopwatch.ElapsedMilliseconds);
// The same photos decoded to bitmaps: every pixel is held in memory and encoded to JPEG again.
stopwatch.Restart();
using (var writer = new PdfWriter("PlaceJpegDecoded.pdf"))
using (var graphics = writer.GetGraphics())
{
writer.Compression = CompressionType.Jpeg;
foreach (var photo in photos)
{
using (var bitmap = new Bitmap(photo))
{
writer.AddPage(bitmap.Width, bitmap.Height, bitmap.DpiX, bitmap.DpiY);
graphics.DrawImage(bitmap, 0, 0);
}
}
}
Console.WriteLine("Bitmap: {0} ms", stopwatch.ElapsedMilliseconds);
Input
Venice.jpg
Copenhagen_CMYK.jpg
Output
PlaceJpegWithoutRecompression.pdf
DownloadPlaceJpegWithoutRecompression.png
PlaceJpegWithoutRecompression.txt
CompressedImage: 224 ms
Bitmap: 411 ms
Used APIs
- Aurigma.GraphicsMill.Bitmap.DpiX
- Aurigma.GraphicsMill.Bitmap.DpiY
- Aurigma.GraphicsMill.Codecs.CompressionType
- Aurigma.GraphicsMill.Codecs.PdfWriter
- Aurigma.GraphicsMill.Codecs.PdfWriter.AddPage(Single,Single,Single,Single)
- Aurigma.GraphicsMill.Codecs.PdfWriter.Compression
- Aurigma.GraphicsMill.Codecs.PdfWriter.GetGraphics
- Aurigma.GraphicsMill.CompressedImage
- Aurigma.GraphicsMill.CompressedImage.CreateFromFile(String)
- Aurigma.GraphicsMill.CompressedImage.DpiX
- Aurigma.GraphicsMill.CompressedImage.DpiY
- Aurigma.GraphicsMill.Drawing.Graphics.DrawImage(Bitmap,Single,Single)
- Aurigma.GraphicsMill.Drawing.Graphics.DrawImage(Pipeline,Single,Single)