SVG 到 PDF 的转换适用于 Plotly.js 但不适用于 C3.js

SVG to PDF conversion working for Plotly.js but not for C3.js

我正在使用 css2pdf 在 onclick 事件后将我的 svg 图表保存为 pdf。它适用于 plotly.js,但不适用于 c3.js - 请参阅我的 fiddle:http://jsfiddle.net/3hs7cs4f/

我确定它与 c3.js svg 属性有关,但我不知道如何解决这个问题。

代码如下:

<link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="http://www.cloudformatter.com/Resources/Pages/CSS2Pdf/Scrip /xeponline.jqplugin.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.js"></script>
</head>

<body>
<br><br>
  <!-- Source and on-click event for plotly.js -->
  <div id="plotly_chart" style="width: 90%; height: 270px"></div>
  <button onclick="return xepOnline.Formatter.Format('plotly_chart',{pageWidth:'11in', pageHeight:'8.5in',render:'download', srctype:'svg'});">Get plotly_PDF</button>

  <!-- Source and on-click event for c3.js-->
  <div id="c3_chart" style="width: 90%; height: 270px"></div>
  <button onclick="return xepOnline.Formatter.Format('c3_chart',{pageWidth:'11in', pageHeight:'8.5in',render:'download', srctype:'svg'});">Get c3_PDF</button>

<!-- JAVASCRIPT for plotly.js chart -->
<script type="text/javascript">
  Chart = document.getElementById('plotly_chart');

 Plotly.plot( Chart, [{
   x: [1, 2, 3, 4, 5],
   y: [1, 2, 4, 8, 16] }], { 
   margin: { t: 0 } } );
</script>

<!-- JAVASCRIPT for j3.js chart -->
<script type="text/javascript">
   var chart = c3.generate({
   bindto: '#c3_chart',
   padding: {
       top: 10,
       right: 70,
       bottom: 50,
       left: 75,
   },
   data: {
       columns: [
           ['data1', 100, 200, 150, 300, 200],
           ['data2', 400, 500, 250, 700, 300],
       ]
   }});
</script>

我尝试了很多其他方法来保存我的 c3.js 图表,但其中 none 效果令人满意。唯一有效的是来自 annatomka 的 ng-c3 导出器,它使用 AngularJS 模块 (https://github.com/annatomka/ng-c3-export)。然而,这个并不能处理我手中的所有 css 设置,而且下载的 png 的质量受屏幕分辨率的限制。因此,我真的很想使用 pdf 导出器,我发现可以处理所有 css 设置的是 css2pdf。但也非常感谢任何其他关于如何将 c3 图表保存为 pdf 的建议。感谢您的帮助!

正如我在上面的评论中所怀疑的那样,c3 绘制的 SVG 缺少 SVG 名称空间。 Css2PDF 要求 SVG 在此命名空间中。

请参阅 http://www.cloudformatter.com/CSS2Pdf.APIDoc.FAQ,第一个常见问题解答,因为它是第一个问题。

为了解决这个问题,我添加了一些小技巧,以便在打印之前将命名空间属性注入到该图中。我相信有更好的方法,但是这个 fiddle 表明你的结果有效。

<script>
   function addnsandprint(){
     $('#c3_chart').find('svg').attr('xmlns','http://www.w3.org/2000/svg');
     xepOnline.Formatter.Format('c3_chart',{pageWidth:'11in', 
        pageHeight:'8.5in',render:'download', srctype:'svg'});
   }
</script>

Fiddle: http://jsfiddle.net/3hs7cs4f/9/

结果:

注意:如果您的 SVG 使用 xlink,您还需要添加“http://www.w3.org/1999/xlink”的 "xmlns:xlink" 属性。为了安全格式化,我会将两者都添加到您的代码中。