Programing/JavaScript

자바스크립트 javascript 페이지 인쇄하기 window.print() document.write()

리커니 2017. 12. 22.
반응형

 

자바스크립트 javascript 페이지 인쇄하기 window.print() document.write()

 

자바스크립트에서 별도의 페이지를 만들지 않고, 특정 버튼을 클릭했을 때

새로운 window객체를 만들어 인쇄 페이지를 만드는 방법을 알아보도록 하겠습니다.

 

1
2
3
4
$('.print').click(function(){
    const completeParam = makeHtml();
    reportPrint(completeParam);
}
cs

 

print라는 클래스명을 가진 버튼을 클릭 시

makeHtml 함수에서 인쇄할 html 페이지를 만들어 리턴 받습니다.

 

1
2
3
4
5
6
7
8
9
10
function makeHtml(){
    const obj = {html : ''};
    let html = '<div class="printPop">';
    .
    .
    .
    html += '</div>';    
    obj.html = html;
    return obj;
}
cs

 

그 다음 reportPrint 함수에 만들어진 html을 포함하는 object를 넘겨줍니다.

reportPrint 함수는 받은 html 파라메터를 받아 새로운 window 객체를 만들어

임시로 보여질 페이지를 동적으로 생성한 후 인쇄기능을 실행합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function reportPrint(param){
    const setting = "width=890, height=841";
    const objWin = window.open('''print', setting);
    objWin.document.open();
    objWin.document.write('<html><head><title>분석 레포트 </title>');
    objWin.document.write('<link rel="stylesheet" type="text/css" href="${ctx }/resource/css/common.css"/>');
    objWin.document.write('</head><body>');
    objWin.document.write(param.html);
    objWin.document.write('</body></html>');
    objWin.focus(); 
    ojWin.document.close();
 
    objWin.print();
    objWin.close();
}
cs

 

css가 필요할 경우 위의 6번째 라인과 같이 추가합니다.

print 함수는 dom객체의 body만 출력하기 때문에 <body> 태그 내에 파라메터로 넘겨받은 html 을 추가합니다.

 

 

 

이렇게 구현할 시에 IE에서는 정상동작 하지만, chrome의 경우 제대로된 페이지가 출력이 안되는 경우가 있습니다.

원인은 위의 8번째 라인에서 param.html에 부하가 있는 로직이 있을 시에 로딩이 완전히 되지 않은 상태에서

print 함수를 호출 하기 때문인거 같습니다.

 

그래서 setTimeout 함수를 활용해 약간의 시간차를 두도록 합니다.

(callback 함수를 사용하여도 제대로 출력이 안되는경우가...)

위의 13, 14 번째 라인을 아래와 같이 수정합니다.

 

1
setTimeout(function(){objWin.print();objWin.close();}, 1000);
cs

 

 

 

 

그럼 위와 같이 chrome에서도 정상 동작 하는것을 확인하실 수 있습니다.

반응형

댓글

💲 추천 글