gpt4 book ai didi

javascript - 如何使用 web worker 使用 makepdf 渲染 PDF

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:13:48 29 4
gpt4 key购买 nike

我使用 JavaScript 插件 ( pdfmake ) 成功创建了一个 PDF,它很棒。但是,当我尝试渲染约 8,000 行的库存/分类帐打印输出时,它会卡住一分钟多。

这就是我通常声明我的 docDefinition 的方式

var docDefinition = { 
pageOrientation: orientation,
footer: function(currentPage, pageCount) { return {text: currentPage.toString() + ' / ' + pageCount, fontSize:8, alignment:'center'}; },
content:[
printHeader,
{ fontSize: 8, alignment: 'right', style: 'tableExample',
table: {
widths: width,
headerRows: 1, body: arr },
layout: 'lightHorizontalLines' }] }

在哪里

var printHeader =   [ { text: 'COMPANY NAME',alignment:'center' },
{ text: 'Address 1',alignment:'center' },
{ text: 'Address 2',alignment:'center' },
{ text: 'Additional Details,alignment:'center' },
{ text: 'document title',alignment:'center' }];

 var arr = [[{"text":"","alignment":"left"},"text":"Date","alignment":"left"},
{"text":"Trans #","alignment":"left"},{"text":"Description","alignment":"left"},
{"text":"Ref #","alignment":"left"},{"text":"Debit","alignment":"left"},
{"text":"Credit","alignment":"left"},{"text":"Amount","alignment":"left"},
{"text":"Balance","alignment":"left"}],[{"text":"ACCOUNT : Merchandise Inventory","alignment":"left","colSpan":8},"","","","","","","",
{"text":"1,646,101.06"}],["","10/13/2015","ST#0094",{"text":"","alignment":"left"},{"text":"","alignment":"left"},"546.94","0.00","546.94","1,646,648.00"],[{"text":"Total","alignment":"left","bold":true},"","","","",
{"text":"546.94","alignment":"right","bold":true},
{"text":"0.00","alignment":"right","bold":true},
{"text":"","alignment":"right","bold":true},
{"text":"546.94","alignment":"right","bold":true}],[{"text":"ACCOUNT : Accounts Payable-Main","alignment":"left","colSpan":8},"","","","","","","",
{"text":"-1,741,953.62"}],["","10/13/2015","ST#0094",
{"text":"","alignment":"left"},
{"text":"","alignment":"left"},"0.00","546.94","-546.94","-1,742,500.56"],
[{"text":"Total","alignment":"left","bold":true},"","","","",
{"text":"0.00","alignment":"right","bold":true},
{"text":"546.94","alignment":"right","bold":true},
{"text":"","alignment":"right","bold":true},
{"text":"-546.94","alignment":"right","bold":true}]

生成 file .

我搜索了 web workers,发现它可以解决这个 UI 卡住问题。所以我尝试为它创建一个网络 worker :

$('#makepdf').click(function(){
var worker = new Worker("<?php echo URL::to('/'); ?>/js/worker.js");
worker.addEventListener('message',function(e){
console.log('Worker said: ',e.data);
},false);

worker.postMessage(docDefinition);

//worker.js

self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);

console.log() 的输出:

Worker said: Object {pageOrientation: "portrait", content: Array[7]} its logging correctly the json structure.

到目前为止一切顺利。但是在我将 pdfmake.min.jsvfs_font.js 添加到 worker 之后,我得到了错误 Uncaught TypeError: Cannot read property 'createElementNS' of undefined.

我什至在开始使用 worker 之前就收到了错误。

能否用pdfmake插件实现web worker?

最佳答案

简单的回答

只需提供一个虚拟构造函数:

var document = { 'createElementNS': function(){ return {} } };
var window = this;
importScripts( 'pdfmake.min.js', 'vfs_fonts.js' );

或者,如果您认为它太脏,请导入 XML-JS (仅 60k)并为 pdfmake 创建一个虚拟文档.

importScripts( 'tinyxmlw3cdom.js' );
var window = this;
var document = new DOMDocument( new DOMImplementation() );
importScripts( 'pdfmake.min.js', 'vfs_fonts.js' );

解释

已知 pdfmake 是 incompatible与 worker 。

就其本身而言,pdfmake does not use创建元素NS。然而它的缩小脚本 pdfmake.min.js做,显然是为了创建一个下载链接。

无论如何我们都不需要下载链接,所以只给它一个虚拟对象让它开心(暂时)。

如果将来它需要一个真正的 DOM,坏消息是文件是unavailable在网络 worker 中。好消息是我们有一个纯 javascript 实现。 Download XML-JS,提取并找到 tinyxmlw3cdom.js,导入它,您可以创建一个功能文档。

除了文档,自vfs_fonts.js通过window变量获取pdfmake,需要引入window作为global的别名。

对我来说,这些步骤使 pdfmake 在 web worker 中工作。

保存文件需要将pdfmake提供的base64数据转换成二进制下载。许多脚本可用,例如 download.js .在下面的代码中,我使用了 FileSaver .


代码

我的 worker 是 Builder可以缓存。如果您在服务器端组成工作人员,你可以摆脱堆栈和构建函数并直接调用pdfmake,使两个 js 代码更加简单。

主要 HTML:

<script src='FileSaver.min.js'></script>
<script>
function base64ToBlob( base64, type ) {
var bytes = atob( base64 ), len = bytes.length;
var buffer = new ArrayBuffer( len ), view = new Uint8Array( buffer );
for ( var i=0 ; i < len ; i++ )
view[i] = bytes.charCodeAt(i) & 0xff;
return new Blob( [ buffer ], { type: type } );
}
//////////////////////////////////////////////////////////

var pdfworker = new Worker( 'worker.js' );

pdfworker.onmessage = function( evt ) {
// open( 'data:application/pdf;base64,' + evt.data.base64 ); // Popup PDF
saveAs( base64ToBlob( evt.data.base64, 'application/pdf' ), 'General Ledger.pdf' );
};

function pdf( action, data ) {
pdfworker.postMessage( { action: action, data: data } );
}

pdf( 'add', 'Hello WebWorker' );
pdf( 'add_table', { headerRows: 1 } );
pdf( 'add', [ 'First', 'Second', 'Third', 'The last one' ] );
pdf( 'add', [ { text: 'Bold value', bold: true }, 'Val 2', 'Val 3', 'Val 4' ] );
pdf( 'close_table' );
pdf( 'add', { text: 'This paragraph will have a bigger font', fontSize: 15 } );
pdf( 'gen_pdf' ); // Triggers onmessage when it is done

// Alternative, one-size-fit-all usage
pdf( 'set', { pageOrientation: 'landscape', footer: { text: 'copyright 2015', fontSize: 8, alignment:'center'}, content:[ "header", { fontSize: 8, alignment: 'right', table: { headerRows: 1, body: [[1,2,3],[4,5,6]] } }] } );
pdf( 'gen_pdf' );

</script>

worker :

//importScripts( 'tinyxmlw3cdom.js' );
//var document = new DOMDocument( new DOMImplementation() );
var document = { 'createElementNS': function(){ return {} } };
var window = this;
importScripts( 'pdfmake.min.js', 'vfs_fonts.js' );

(function() { 'use strict';

var doc, current, context_stack;

function set ( data ) {
doc = data;
if ( ! doc.content ) doc.content = [];
current = doc.content;
context_stack = [ current ];
}
set( {} );

function add ( data ) {
current.push( data );
}

function add_table ( template ) {
if ( ! template ) template = {};
if ( ! template.table ) template = { table: template };
if ( ! template.table.body ) template.table.body = [];
current.push( template ); // Append table
push( template.table.body ); // Switch context to table body
}

function push ( data ) {
context_stack.push( current );
return current = data;
}

function pop () {
if ( context_stack.length <= 1 ) return console.warn( "Cannot close pdf root" );
context_stack.length -= 1;
return current = context_stack[ context_stack.length-1 ];
}

function gen_pdf() {
pdfMake.createPdf( doc ).getBase64( function( base64 ) {
postMessage( { action: 'gen_pdf', base64: base64 } );
} );
}

onmessage = function( evt ) {
var action = evt.data.action, data = evt.data.data;
switch ( action ) {
case 'set': set( data ); break;
case 'add': add( data ); break;
case 'add_table' : add_table( data ); break;
case 'close_table': pop(); break;
case 'gen_pdf': gen_pdf(); break;
}
};

})();

关于javascript - 如何使用 web worker 使用 makepdf 渲染 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32689932/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com