如何在XAML中嵌入JPEG图像生成XPS

本文关键字:图像 JPEG XPS XAML | 更新日期: 2023-09-27 18:11:58

我正在使用XpsDocument类动态生成一个XPS文件。在我的XAML模板中,我将JPEG图像嵌入到图像容器中。然而,结果XPS中嵌入的图像总是PNG图像 -导致某些类型的图像的文件非常大。

似乎文档作者将渲染的图像解释为位图,然后将其保存为PNG

下面是生成XPS的代码:
void ConvertToXps(IEnumerable<FixedDocument> fixedDocuments, Stream outputStream)
{
    var package = Package.Open(outputStream, FileMode.Create);
    var xpsDoc = new XpsDocument(package, CompressionOption.Normal);
    var xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
    // XPS documents are built using fixed document sequences.
    var fixedDocSeq = new FixedDocumentSequence();
    // A4 = 210 x 297 mm = 8.267 x 11.692 inches = 793.632 * 1122.432 dots
    fixedDocSeq.DocumentPaginator.PageSize = new Size(793.632, 1122.432);
    foreach (var fixedDocument in fixedDocuments)
    {
        var docRef = new DocumentReference();
        docRef.BeginInit();
        docRef.SetDocument(fixedDocument);
        docRef.EndInit();
        ((IAddChild)fixedDocSeq).AddChild(docRef);
    }
    // Write out our fixed document to XPS.
    xpsWriter.Write(fixedDocSeq.DocumentPaginator);
    xpsDoc.Close();
    package.Close();
}

Q:如何强制我的XAML渲染图像在生成的XPS中保存为JPEG ?

如何在XAML中嵌入JPEG图像生成XPS

我认为你必须改变创建XPS文档的方式。

var package = Package.Open(outputStream, FileMode.Create);
var xpsDoc = new XpsDocument(package, CompressionOption.Normal);
var xpsWriter = xpsDoc.AddFixedDocumentSequence();
var fixedDocSeq = xpsDoc.GetFixedDocumentSequence();
// A4 = 210 x 297 mm = 8.267 x 11.692 inches = 793.632 * 1122.432 dots
fixedDocSeq.DocumentPaginator.PageSize = new Size(793.632, 1122.432);
foreach (var fixedDocument in fixedDocuments)
{
    var docWriter = xpsWriter.AddFixedDocument();
    var pageWriter = docWriter.AddFixedPage();
    var image = pageWriter.AddImage(XpsImageType.JpegImageType);
    Stream imageStream = image.GetStream();
    //Write your image to stream
    //Write the rest of your document based on the fixedDocument object
}

这里的关键是用docWriter.AddFixedPage();获得IXpsFixedPageWriter。这允许您重新创建文档,在您想要的位置添加图像。

不确定是否可以编辑已经创建的FixedDocument