我尝试使用 Javascript 按照本网站的方法将 amcharts 导出为 PDF
[Codepen](https://codepen.io/team/amcharts/pen/35076c4d7b6eef7764dacc61f72adadc)
步骤,PDF出现乱码(中文),我想用UTF-8,怎么解决?为什么图表的分辨率这么低?谢谢。 enter image description here
html
<h2 id="OPASS" class="display-5 col-md-offset-4 col-md-12">測試圖表</h2>
JavaScript
var downloadPDF = function() {
console.log("Starting export...");
var ids = ["chartdiv", "Passion_chart", "Anchor_chart", "Switch_chart", "Synergy_chart"];
var charts = {}, charts_remaining = ids.length;
for (var i = 0; i < ids.length; i++) {
for (var x = 0; x < AmCharts.charts.length; x++) {
if (AmCharts.charts[x].div.id == ids[i])
charts[ids[i]] = AmCharts.charts[x];
}
}
for (var x in charts) {
if (charts.hasOwnProperty(x)) {
var chart = charts[x];
chart["export"].capture({}, function() {
this.toJPG({}, function(data) {
// Save chart data into chart object itself
this.setup.chart.exportedImage = data;
// Reduce the remaining counter
charts_remaining--;
// Check if we got all of the charts
if (charts_remaining == 0) {
// Yup, we got all of them
// Let's proceed to putting PDF together
generatePDF();
}
});
});
}
}
function generatePDF() {
// Log
console.log("Generating PDF...");
// Initiliaze a PDF layout
var layout = {
"content": []
};
// Let's add a custom title
layout.content.push({
"text": document.getElementById("OPASS").innerHTML,
"fontSize": 24
});
// Now let's grab actual content from our <p> intro tag
layout.content.push({
"text": document.getElementById("intro").innerHTML
});
// Add bigger chart
layout.content.push({
"image": charts["chartdiv"].exportedImage,
"fit": [523, 300]
});
chart["export"].toPDF(layout, function(data) {
this.download(data, "application/pdf","amCharts.pdf");
});
}
}
最佳答案
PDFMake,AmCharts 用于 PDF 导出的库,不支持开箱即用的中文及其使用的默认 Roboto 字体(问题跟踪器中有大量关于此的问题,例如 this one )。您必须使用包含中文字符的字体创建自定义 vfs_fonts.js
文件,并使用 step by step tutorial 代替捆绑的字体文件。由 pdfmake 开发者提供。我看的 github issues 似乎推荐使用“Microsoft YaHei”。
创建自定义字体文件后,您需要手动将 pdfMake.js 以及自定义 vfs_fonts.js 文件包含到您的页面中,然后是对 window.pdfMake.fonts 的引用,否则它知道使用那个而不是默认的 Roboto 字体。
<script src="./amcharts/plugins/export/libs/pdfMake/pdfMake.js" type="text/javascript"></script>
<script src="vfs_fonts.js" type="text/javascript"></script>
<script type="text/javascript">
pdfMake.fonts = {
"Microsoft Yahei": {
"normal": 'name of font.tff', //replace with the name of the ttf font file
"bold": 'name of bold font.ttf',
"italics": 'name of italics font.ttf',
"bolditalics": 'name of bold italics font.ttf'
}
}
// ...
AmCharts.makeChart( {
"export": {
"enabled": true,
"pdfMake": {
defaultStyle: {
font: "Microsoft YaHei"
}
},
},
...
} );
</script>
关于javascript - Amcharts 中的乱码文本导出为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46536709/