使用从代码创建的数据打印iframe不起作用

时间:2018-01-05 17:20:14

标签: javascript pdf iframe jspdf node-pdfkit

我在pdfkit的分支上有一些示例代码:

https://github.com/EricG-Personal/pdf_printing/tree/feature/from_pdfkit

我用来创建一个带pdfkit的简单PDF的代码是:

var doc = new PDFDocument( { size: 'legal' } );

this.stream = doc.pipe( blobStream() );

doc.fontSize( 9 );
doc.font( 'Times-Roman' );
doc.text( "hello, world! I'm really here" );
doc.rect( 10, 10, 100, 100 ).stroke();
doc.end();

this.stream.on( 'finish', function() 
{
    console.log( "Stream Finished" );

    this.setState( { pdfData: this.stream.toBlobURL( 'application/pdf' ) } );
}.bind( this ) );

对于jsPDF - https://github.com/EricG-Personal/pdf_printing/tree/feature/from_jspdf

var doc = new jsPDF({unit: 'pt', format: 'legal'});
var someText = "hello, world!";
var topCoordinate = 72;
var leftCoordinate = 72;
var padding = 8;

doc.setFont( "helvetica" );
doc.setFontSize( 24 );

var lineHeight      = doc.getLineHeight();
var textWidth       = doc.getTextWidth( someText );
var rectHeight      = ( lineHeight + ( padding * 2 ) );
var halfRectHeight  = rectHeight / 2;
var halfLineHeight  = lineHeight / 2;
var textYCoordinate = topCoordinate + halfRectHeight + halfLineHeight;

console.log( "Height: " + lineHeight );
console.log( "Width: " + textWidth );

doc.setDrawColor( 255, 0, 0 );
doc.rect( leftCoordinate, topCoordinate, textWidth, rectHeight );
doc.text( someText, leftCoordinate + padding, textYCoordinate );

doc.setDrawColor( 0, 0, 0 );
doc.rect( leftCoordinate, textYCoordinate - lineHeight, textWidth, lineHeight );

var blob   = doc.output( 'bloburl' );
var mythis = this;

setTimeout( function() 
{ 
    console.log( "Setting State" );

    mythis.setState({pdfData: blob});
}, 5000);

在这两种情况下,PDF数据都会在iframe中正确呈现,我最终会调用:

window.frames["pdf_doc"].focus();
window.frames["pdf_doc"].print();

当iframe的onLoad函数触发时。

但是,实际要打印的页面是空白的。

1 个答案:

答案 0 :(得分:0)

它适用于Safari,但不适用于Firefox。我认为您使用错误的数组键:

window.frames[0].focus();
window.frames[0].print();

适合我。

console.log(window.frames);

查看文档:{​​{3}}