应用场景:
客户在创建前后端分离的应用时,前端只用于做一些基本的数据展示,如果涉及大量的数据或报表生成,建议放在服务器端展示,本文主要分享如何在服务器端使用ActiveReportsJS 实现报表导出PDF功能

Demo下载:

https://gcdn.grapecity.com.cn/forum.php?mod=attachment&aid=MTIzMjQwfGMwM2JkNWVhfDE2MjM3MjI5NzF8MjkzODJ8ODgwNzA%3D

环境准备:
node.js v14.15.0+Headless 无头浏览器

操作步骤:

  1. 添加资源文件
    image.png
  2. 配置资源和文件
const puppeteer = require('puppeteer');
const fs = require('fs');
var static = require('node-static');
var http = require('http');

var file = new(static.Server)(__dirname + '/resources');

http.createServer(function (req, res) {
  file.serve(req, res);
}).listen(9999);

const fonts = [
    {
        name: 'Montserrat',
        source: 'Montserrat-Regular.ttf'
    },
    {
        name: 'Montserrat',
        source: 'Montserrat-Medium.ttf',
        weight: 500
    }
];

3. 调用浏览器并初始化 调用ARJS 导出PDF文件

(async () => {
    const browser = await puppeteer.launch({headless: true});
    const page = await browser.newPage();
    await page.goto(`http://localhost:9999/host.html`);
    //await page.goto(`${__dirname}/resources/host.html`);
    const pdfString =await page.evaluate(({reportUrl, fonts}) =>        
        new Promise(async (resolve, reject) => {
            // await GC.ActiveReports.Core.FontStore.registerFonts(fonts);
            const report = new GC.ActiveReports.Core.PageReport();
            await report.load(reportUrl);
            const doc = await report.run();
            const result = await GC.ActiveReports.PdfExport.exportDocument(doc, {fonts: fonts, info: {author: 'GrapeCity'}});
            const reader = new FileReader();
            reader.readAsBinaryString(result.data);
            reader.onload = () => resolve(reader.result);
            reader.onerror = () => reject('Error occurred while reading binary string');
        }), {reportUrl: 'SimpleTable.rdlx-json', fonts: fonts});

    const pdfData = Buffer.from(pdfString, 'binary');
    fs.writeFileSync(`${__dirname}/out115.pdf`, pdfData);
    console.log('done');   
    process.exit(0);
})();

LanLan_Guo
14 声望4 粉丝

研究报表已经7年有余,略懂一二。期望能够成为报表专家,为大家能够提供报表咨询服务。