2016-09-24 99 views
1

我有一個帶有SVG標記的示例測試頁,我試圖用PhantomJS將其另存爲SVG文件。我可以使用PhantomJS進入測試頁面,但是我無法弄清楚如何找到並保存svg。以下是我試圖做到這一點,以及我卡在哪裏。用PhantomJS保存SVG

  1. 瞭解它們與網頁
  2. 試圖找到SVG標籤與document.getElementsByTagName( 'SVG')
  3. 什麼從這裏做什麼?我可以看到幻影返回一個巨大的對象,但無法找到他們的網站上有關如何處理這件事。我該如何將這個對象轉換成svg文件?

的testpage看起來是這樣的:

<HTML> 

This is a Testpage. You like it, don't you? 

<svg xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink"> 

    <defs> 
    <linearGradient id="myLinearGradient1" 
        x1="0%" y1="0%" 
        x2="0%" y2="100%" 
        spreadMethod="pad"> 
     <stop offset="0%" stop-color="#00cc00" stop-opacity="1"/> 
     <stop offset="100%" stop-color="#006600" stop-opacity="1"/> 
    </linearGradient> 
    </defs> 

    <rect x="10" y="10" width="75" height="100" rx="10" ry="10" 
    style="fill:url(#myLinearGradient1); 
      stroke: #005000; 
      stroke-width: 3;" /> 

</svg> 

</HTML> 

和PhantomJS腳本

var page = require('webpage').create(); 

console.log('The default user agent is ' + page.settings.userAgent); 

function getSVG(link, callback) { 
    page.open(link, function(status) { 
     if (status !== 'success') { 
      console.log('Unable to access network'); 
     } else { 
      var ua = page.evaluate(function() { 
       return document.getElementsByTagName('svg'); 
      }); 
      // Don't know what to do here 
     } 
     phantom.exit(); 
     callback(); 
    }); 
} 

getSVG('testpage', function() { 
    console.log('done'); 
}); 

回答

1
var svg = page.evaluate(function(){ 
    return document.querySelector("svg").outerHTML; 
}); 

var fs = require("fs"); 
fs.write("file.svg", svg); 

應該讓你開始,但這可能還不夠,因爲SVG可以被操縱與CSS。