none
How to fit the image canvas to the media size (A4) in print Charm preview, and keep the image ratio

    Question

  • Hi, 

    I met a problem that I need to print an image canvas. I use the CSS3 Media Queries, but the image is stretched as below:

    the image in the preview is stretched

    I also checked the Photo app by Microsoft, the image can be kept by ratio and will fit the page automatically, see below:

    Photo app by Microsoft, keeps the image ratio

    My code:

    default.html

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>imgLoadTest</title>
    
        <!-- WinJS references -->
        <link rel="stylesheet" type="text/css" href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" />
        <script type="text/javascript" src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
        <script type="text/javascript" src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
    
        <!-- imgLoadTest references -->
        <link href="/css/default.css" rel="stylesheet">
        <script src="/js/default.js"></script>
        <style media="print" type="text/css">
            .noprint {
                display: none;
            }
    
        </style>
    </head>
    <body style="">
        <div class="noprint">
            <button id="picker" style="border: 1px solid white">open</button>
    
            <button id="printButton" style="display: none;">Print</button>
    
            <p id="output"></p>
        </div>
        <canvas id="mainCanvas" class="mainCanvas"></canvas>
    </body>
    </html>
    

    default.js

    (function () {
        "use strict";
    
        var app = WinJS.Application;
        app.imgLoaded = false;
        app.ctx = null;
        app.canW = null;
        app.canH = null;
    
        var id = function (ele) {
            return document.getElementById(ele);
        };
    
        app.onactivated = function (eventObject) {
            if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                    // TODO: This application has been newly launched. Initialize 
                    // your application here.
    
                    id('picker').onclick = function () {
    
                        var picker = new Windows.Storage.Pickers.FileOpenPicker();
                        picker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
                        picker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
                        picker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg", ".bmp"]);
    
                        picker.pickSingleFileAsync().then(function (file) {
                            if (!file) {
                                console.log('file is not got...');
                                return;
                            }
    
                            //app.clear();
                            if (app.ctx && app.canW && app.canH) {
                                id('output').innerHTML = 'clearing...';
                                app.ctx.clearRect(0, 0, app.canW, app.canH);
                                var mainCanvas = id('mainCanvas');
                                mainCanvas.width = 0;
                                mainCanvas.height = 0;
                                app.imgLoaded = false;
                                id('output').innerHTML = 'cleared';
                            }
    
                            file.openReadAsync().then(function (randomAccessStream) {
                                /// migrate from the 8250 to 8375 because the StorageFile no longer supported for createObjectURL. @2012.05.09
                                var blob = window.MSApp.createBlobFromRandomAccessStream("image/jpg", randomAccessStream);
                                var src = window.URL.createObjectURL(blob);
                                var canvasImage = document.createElement('img');
                                canvasImage.onerror = function () {
                                    id('output').innerHTML = 'img load error...';
                                };
                                canvasImage.onload = function () {
                                    id('output').innerHTML = 'img loaded...';
    
                                    console.log('onload starts at: ' + (new Date()).valueOf());
                                    console.log(canvasImage.complete);
    
                                    var mainCanvas = id('mainCanvas');
                                    var context = mainCanvas.getContext("2d");
                                    app.ctx = context;
                                    mainCanvas.width = canvasImage.naturalWidth;
                                    mainCanvas.height = canvasImage.naturalHeight;
    
                                    app.canW = mainCanvas.width;
                                    app.canH = mainCanvas.height;
    
                                    id('output').innerHTML = 'drawing img to canvas...';
    
                                    context.drawImage(this, 0, 0, mainCanvas.width, mainCanvas.height);
                                    console.log('draw canvas finish at: ' + (new Date()).valueOf());
    
                                    //Register for print contract
                                    var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
                                    printManager.onprinttaskrequested = onPrintTaskRequested;
    
                                    //Add event handler for Print button click
                                    id("printButton").style.display = 'block';
                                    id("printButton").addEventListener("click", printButtonClick, false);
    
                                    id('output').innerHTML = 'complete drawing img to canvas with dimensions: ' + mainCanvas.width + ' x ' + mainCanvas.height;
    
                                    app.imgLoaded = true;
                                    console.log('======================================================');
    
                                    window.URL.revokeObjectURL(src);
                                    canvasImage = undefined;
                                };
    
                                id('output').innerHTML = 'loading img to blob...';
                                canvasImage.src = src;
                                console.log('src is set at: ' + (new Date()).valueOf());
    
                            });
    
    
                        });
                    };
                } else {
                    // TODO: This application has been reactivated from suspension. 
                    // Restore application state here.
                }
                WinJS.UI.processAll();
            }
        };
    
        app.oncheckpoint = function (eventObject) {
            // TODO: This application is about to be suspended. Save any state
            // that needs to persist across suspensions here. You might use the 
            // WinJS.Application.sessionState object, which is automatically
            // saved and restored across suspension. If you need to complete an
            // asynchronous operation before your application is suspended, call
            // eventObject.setPromise(). 
        };
    
        app.start();
    
        // Function to process the print button click
        function printButtonClick() {
            Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
        }
    
        function onPrintTaskRequested(printEvent) {
            var printTask = printEvent.request.createPrintTask("Print Sample", function (args) {
                args.setSource(MSApp.getHtmlPrintDocumentSource(document));
            });
    
            // Enumerate the printer settings you want to show.
            // They appear in the print window in the same order
            // that you list them here
            printTask.options.displayedOptions.clear();
            printTask.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.copies);
            printTask.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.mediaSize);
            printTask.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.orientation);
            printTask.options.displayedOptions.append(Windows.Graphics.Printing.StandardPrintTaskOptions.duplex);
    
            //You may even preset the values on a printer setting
            printTask.options.mediaSize = Windows.Graphics.Printing.PrintMediaSize.isoA4;
        }
    })();
    

    default.css

    body {
    }
    
    @media screen and (-ms-view-state: fullscreen-landscape) {
    }
    
    @media screen and (-ms-view-state: filled) {
    }
    
    @media screen and (-ms-view-state: snapped) {
    }
    
    @media screen and (-ms-view-state: fullscreen-portrait) {
    }
    
    @media print {
        .mainCanvas {
            width:100%;
            max-height:100%;
        }
    }
    

    The test environment  is windows 8 b8400, vs 2012rc.


    sun

    Wednesday, June 13, 2012 7:25 AM

Answers

All replies