Andrey Potapov
Andrey Potapov

Reputation: 67

Saving a FixedDocument with images to XPS file

I've saved a FixedDocument to XPS file for example:

void SaveDocument(FixedDocument document, string filePath)
{
    var xps = new XpsDocument(
        filePath, FileAccess.Write, CompressionOption.Maximum);

    var writer = XpsDocument.CreateXpsDocumentWriter(xps);
    writer.Write(document);

    xps.Close();
}

Then I've opened XPS file as ZIP archive and saw my images are kept as PNG files. How can I change image file format to JPG?

Upvotes: 2

Views: 2248

Answers (1)

JounceCracklePop
JounceCracklePop

Reputation: 348

I had the same problem: my file size was too big because photographs were being embedded as png instead of jpeg. I fixed it by converting all png files to jpeg in the package. I kept the URIs the same to avoid having to update references to the image, but this means the internal URI of your jpegs will end in a misleading ".png". Obviously this gets more complicated if you want to pick and choose which images you convert to jpeg.

public static void ReplacePngsWithJpegs(Package package)
{
    // We're modifying the enumerable as we iterate, so take a snapshot with ToList()
    foreach (var part in package.GetParts().ToList())
    {
        if (part.ContentType == "image/png")
        {
            using (var jpegStream = new MemoryStream())
            using (var image = System.Drawing.Image.FromStream(part.GetStream()))
            {
                image.Save(jpegStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                jpegStream.Seek(0, SeekOrigin.Begin);

                // Cannot access Uri after part is removed, so store it
                var uri = part.Uri; 

                package.DeletePart(uri);

                var jpegPart = package.CreatePart(uri, "image/jpeg");
                jpegStream.CopyTo(jpegPart.GetStream());
            }
        }
    }
}

Upvotes: 1

Related Questions