javascript 从浏览器仅打印 SVG

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21660843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:25:02  来源:igfitidea点击:

Print Only SVG from Browser

javascriptsvg

提问by SixDegrees

I'm working on a webpage that will dynamically render SVG graphics based on user interaction. Once complete, I would like the user to be able to print the graphics only - not simply print the webpage they reside on and the SVG along with it, but just the SVG. Also, the printed version will ideally be drawn slightly differently than the onscreen browser version. Is this sort of thing possible with current browsers and SVG?

我正在开发一个基于用户交互动态呈现 SVG 图形的网页。完成后,我希望用户能够仅打印图形 - 不仅仅是打印他们所在的网页和 SVG,而只是打印 SVG。此外,理想情况下,打印版本的绘制方式与屏幕浏览器版本略有不同。当前的浏览器和 SVG 可以实现这种事情吗?

In Java, I can provide either a paint engine or a print engine to my applications drawing routine, and this handles the same problem simply. I'm a novice to SVG, however, and I can't determine whether some similar mechanism exists.

在 Java 中,我可以为我的应用程序绘制例程提供绘制引擎或打印引擎,这可以简单地处理相同的问题。但是,我是 SVG 的新手,我无法确定是否存在某些类似的机制。

回答by Francis Hemsher

You can use jQuery. Assume you have your svg in a DIV(svgDiv) in the web page, include a print button that calls the following, where the root svg has an id=mySVG, to get width/height, or use the svgDiv width/height. This will print the view that is currently in the svg window.

您可以使用 jQuery。假设您的 svg 在网页的 DIV(svgDiv) 中,包括一个调用以下内容的打印按钮,其中根 svg 具有 id=mySVG,以获取宽度/高度,或使用 svgDiv 宽度/高度。这将打印当前在 svg 窗口中的视图。

//---print button---
    var printSVG = function()
    {
        var popUpAndPrint = function()
        {
            var container = $('#svgDiv');
            var width = parseFloat(mySVG.getAttribute("width"))
            var height = parseFloat(mySVG.getAttribute("height"))
            var printWindow = window.open('', 'PrintMap',
            'width=' + width + ',height=' + height);
            printWindow.document.writeln($(container).html());
            printWindow.document.close();
            printWindow.print();
            printWindow.close();
        };
        setTimeout(popUpAndPrint, 500);
    };

回答by Robert Longson

You can call window.printto start the printing process from javascript.

您可以调用window.print从 javascript 开始打印过程。

You can make the printed and visible versions different using media queriesE.g.

您可以使用媒体查询使打印版本和可见版本不同,例如

@media print { different css for print SVG }

If you don't want existing stuff on the page to print, use the media query to set it display:none or visibility:hidden.

如果您不想打印页面上的现有内容,请使用媒体查询将其设置为 display:none 或visibility:hidden。