인쇄 뿐?
표시된 div를 어떻게 인쇄합니까 (페이지의 다른 모든 내용을 수동으로 비활성화하지 않고)?
새로운 미리보기 대화 상자를 피하고 싶기 때문에이 내용으로 새 창을 만드는 것은 유용하지 않습니다.
페이지에는 두 개의 테이블이 있으며 그중 하나에는 인쇄하려는 div가 포함되어 있습니다. 테이블은 웹에 시각적 스타일로 스타일이 지정되어 인쇄에 표시되지 않아야합니다.
다음은 CSS 만 사용하는 일반적인 솔루션이며 작동하는 것으로 확인되었습니다.
@media print {
body * {
visibility: hidden;
}
#section-to-print, #section-to-print * {
visibility: visible;
}
#section-to-print {
position: absolute;
left: 0;
top: 0;
}
}
대체 접근법은 그리 좋지 않습니다. display
요소가 있으면 display:none
그 하위 요소가 표시되지 않으므로 사용 하기 까다 롭습니다 . 사용하려면 페이지 구조를 변경해야합니다.
사용 visibility
이 후손을 위해 가시성을 설정할 수 있기 때문에 더 나은 작품. 보이지 않는 요소는 여전히 레이아웃에 영향을 미치므로 section-to-print
왼쪽 상단으로 이동 하여 올바르게 인쇄됩니다.
최소한의 코드로 더 나은 솔루션을 제공합니다.
다음과 같이 ID가있는 div 안에 인쇄 가능한 부분을 넣으십시오.
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
그런 다음 onclick과 같은 이벤트를 추가하고 (위와 같이) 위에서 한 것처럼 div의 ID를 전달하십시오.
이제 정말 간단한 자바 스크립트를 만들어 봅시다 :
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
이것이 얼마나 간단한 지 알 수 있습니까? 팝업, 새 창, 미친 스타일링, jquery와 같은 JS 라이브러리가 없습니다. 정말 복잡한 솔루션의 문제 (답변은 복잡하지 않고 내가 말하는 것이 아닙니다)는 모든 브라우저에서 번역되지 않을 것이라는 사실입니다! 스타일을 다르게하려면 스타일 시트 링크 (media = "print")에 media 속성을 추가하여 확인 된 답변에 표시된대로 수행하십시오.
보풀이없고 가벼우 며 작동합니다.
지금까지의 모든 대답은 상당히 결함이 있습니다 . class="noprint"
모든 것에 추가 하거나 그 display
안에 엉망이 될 것 #printable
입니다.
가장 좋은 해결책은 인쇄 할 수없는 물건을 감싸는 래퍼를 만드는 것입니다.
<head>
<style type="text/css">
#printable { display: none; }
@media print
{
#non-printable { display: none; }
#printable { display: block; }
}
</style>
</head>
<body>
<div id="non-printable">
Your normal page contents
</div>
<div id="printable">
Printer version
</div>
</body>
물론 이것은 HTML에서 물건을 조금 움직일 때 완벽하지 않습니다 ...
jQuery를 사용하면 다음과 같이 간단합니다.
w=window.open();
w.document.write($('.report_left_inner').html());
w.print();
w.close();
인쇄 스타일 시트 를 사용하고 CSS를 사용하여 인쇄 할 내용을 정렬 할 수 있습니까? 자세한 내용 은 이 기사 를 읽으십시오 .
이것은 잘 작동합니다 :
<style type="text/css">
@media print
{
body * { visibility: hidden; }
#printcontent * { visibility: visible; }
#printcontent { position: absolute; top: 40px; left: 30px; }
}
</style>
이것은 "가시성"에서만 작동합니다. "디스플레이"는하지 않습니다. FF3에서 테스트되었습니다.
나는이 답변 중 전체를 좋아하지 않았습니다. 클래스 (printableArea와 같은 클래스)가 있고 그것을 바로 몸의 자식으로 가지고 있다면 인쇄 CSS에서 다음과 같이 할 수 있습니다.
body > *:not(.printableArea) {
display: none;
}
//Not needed if already showing
body > .printableArea {
display: block;
}
가시성을 사용하면 많은 간격 문제와 빈 페이지가 발생할 수 있습니다. 가시성으로 인해 요소 공간이 유지되고 숨겨져 표시가 제거되면서 다른 요소가 공간을 차지할 수 있기 때문입니다.
이 솔루션이 작동하는 이유는 모든 요소를 잡는 것이 아니라 신체의 직접적인 자식 만 숨기고 있기 때문입니다. 디스플레이 CSS가있는 아래의 다른 솔루션은 모든 요소를 숨기고 printableArea 내용의 모든 내용에 영향을 미칩니다.
사용자가 클릭하는 인쇄 버튼이 필요하고 표준 브라우저 인쇄 버튼이 동일한 효과를 가지지 않기 때문에 자바 스크립트를 제안하지 않습니다. 정말로 그렇게해야한다면 본문의 html을 저장하고 원하지 않는 모든 요소를 제거하고 인쇄 한 다음 html을 다시 추가하십시오. 위에서 언급했듯이 위와 같은 CSS 옵션을 사용할 수 있다면 이것을 피할 것입니다.
참고 : 인라인 스타일을 사용하여 인쇄 CSS에 CSS를 추가 할 수 있습니다.
<style type="text/css">
@media print {
//styles here
}
</style>
또는 일반적으로 사용하는 것처럼 링크 태그가 있습니다.
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
id를 인쇄하려는 요소를 지정하십시오
printMe
.이 스크립트를 헤드 태그에 포함하십시오 :
<script language="javascript"> var gAutoPrint = true; function processPrint(){ if (document.getElementById != null){ var html = '<HTML>\n<HEAD>\n'; if (document.getElementsByTagName != null){ var headTags = document.getElementsByTagName("head"); if (headTags.length > 0) html += headTags[0].innerHTML; } html += '\n</HE' + 'AD>\n<BODY>\n'; var printReadyElem = document.getElementById("printMe"); if (printReadyElem != null) html += printReadyElem.innerHTML; else{ alert("Error, no contents."); return; } html += '\n</BO' + 'DY>\n</HT' + 'ML>'; var printWin = window.open("","processPrint"); printWin.document.open(); printWin.document.write(html); printWin.document.close(); if (gAutoPrint) printWin.print(); } else alert("Browser not supported."); } </script>
함수를 호출
<a href="javascript:void(processPrint());">Print</a>
hm ... 인쇄용 스타일 시트 유형 사용 ... 예 :
<link rel="stylesheet" type="text/css" href="print.css" media="print" />
print.css :
div { display: none; }
#yourdiv { display: block; }
<script type="text/javascript">
function printDiv(divId) {
var printContents = document.getElementById(divId).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = "<html><head><title></title></head><body>" + printContents + "</body>";
window.print();
document.body.innerHTML = originalContents;
}
</script>
1 단계 : 헤드 태그 안에 다음 자바 스크립트 작성
<script language="javascript">
function PrintMe(DivID) {
var disp_setting="toolbar=yes,location=no,";
disp_setting+="directories=yes,menubar=yes,";
disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
var content_vlue = document.getElementById(DivID).innerHTML;
var docprint=window.open("","",disp_setting);
docprint.document.open();
docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"');
docprint.document.write('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">');
docprint.document.write('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">');
docprint.document.write('<head><title>My Title</title>');
docprint.document.write('<style type="text/css">body{ margin:0px;');
docprint.document.write('font-family:verdana,Arial;color:#000;');
docprint.document.write('font-family:Verdana, Geneva, sans-serif; font-size:12px;}');
docprint.document.write('a{color:#000;text-decoration:none;} </style>');
docprint.document.write('</head><body onLoad="self.print()"><center>');
docprint.document.write(content_vlue);
docprint.document.write('</center></body></html>');
docprint.document.close();
docprint.focus();
}
</script>
2 단계 : onclick 이벤트로 PrintMe ( 'DivID') 함수를 호출하십시오.
<input type="button" name="btnprint" value="Print" onclick="PrintMe('divid')"/>
<div id="divid">
here is some text to print inside this div with an id 'divid'
</div>
CSS 3을 사용하면 다음을 사용할 수 있습니다.
body *:not(#printarea) {
display: none;
}
JavaScript를 사용하여 콘텐츠를 집어 들고 대신 인쇄 할 수있는 창을 만들었습니다.
산드로의 방법은 훌륭합니다.
여러 printMe 링크, 특히 탭 페이지 및 확장 텍스트에 사용할 수 있도록 조정했습니다.
function processPrint(printMe){
<-여기서 변수를 호출
var printReadyElem = document.getElementById(printMe);
<-변수를 요구하기 위해 printMe 주위의 따옴표를 제거했습니다
<a href="javascript:void(processPrint('divID'));">Print</a>
<-인쇄 할 div ID를 함수에 전달하여 printMe 변수를 div ID로 설정합니다. 작은 따옴표가 필요합니다
printDiv (divId) : 모든 페이지에서 div를 인쇄하는 일반화 된 솔루션입니다.
비슷한 문제가 있었지만 (a) 전체 페이지를 인쇄하거나 (b) 여러 특정 영역 중 하나를 인쇄하려고했습니다. 위의 많은 덕분에 내 솔루션을 사용하면 인쇄 할 div 객체를 지정할 수 있습니다.
이 솔루션의 핵심은 인쇄 된 용지 스타일 시트에 적절한 규칙을 추가하여 요청 된 div (및 그 내용)가 인쇄되도록하는 것입니다.
먼저 필요한 인쇄 CSS를 만들어 모든 것을 억제하십시오 (그러나 인쇄하려는 요소를 허용하는 특정 규칙이 없음).
<style type="text/css" media="print">
body {visibility:hidden; }
.noprintarea {visibility:hidden; display:none}
.noprintcontent { visibility:hidden; }
.print { visibility:visible; display:block; }
</style>
새로운 클래스 규칙을 추가했습니다.
- noprintarea를 사용하면 컨텐츠와 블록 둘 다에서 요소의 인쇄를 억제 할 수 있습니다.
- noprintcontent를 사용하면 div 내의 요소 인쇄를 억제 할 수 있습니다. 컨텐츠는 억제되지만 할당 된 영역은 비어 있습니다.
- 인쇄를 사용하면 인쇄 된 버전에는 표시되지만 화면 페이지에는 표시되지 않는 항목이있을 수 있습니다. 이들은 일반적으로 화면 스타일에 대해 "display : none"을 갖습니다.
그런 다음 세 개의 JavaScript 함수를 삽입하십시오. 첫 번째는 인쇄 용지 스타일 시트를 켜거나 끕니다.
function disableSheet(thisSheet,setDisabled)
{ document.styleSheets[thisSheet].disabled=setDisabled; }
두 번째는 실제 작업을 수행하고 세 번째는 나중에 정리합니다. 두 번째 (printDiv)는 인쇄 용지 스타일 시트를 활성화 한 다음 원하는 div를 인쇄 할 수 있도록 새 규칙을 추가하고 인쇄를 발행 한 다음 최종 하우스 키핑 전에 지연을 추가합니다 (그렇지 않으면 인쇄가 실제로 시작되기 전에 스타일을 재설정 할 수 있음) 끝난.)
function printDiv(divId)
{
// Enable the print CSS: (this temporarily disables being able to print the whole page)
disableSheet(0,false);
// Get the print style sheet and add a new rule for this div
var sheetObj=document.styleSheets[0];
var showDivCSS="visibility:visible;display:block;position:absolute;top:30px;left:30px;";
if (sheetObj.rules) { sheetObj.addRule("#"+divId,showDivCSS); }
else { sheetObj.insertRule("#"+divId+"{"+showDivCSS+"}",sheetObj.cssRules.length); }
print();
// need a brief delay or the whole page will print
setTimeout("printDivRestore()",100);
}
최종 기능은 추가 된 규칙을 삭제하고 전체 페이지를 인쇄 할 수 있도록 인쇄 스타일을 다시 비활성화로 설정합니다.
function printDivRestore()
{
// remove the div-specific rule
var sheetObj=document.styleSheets[0];
if (sheetObj.rules) { sheetObj.removeRule(sheetObj.rules.length-1); }
else { sheetObj.deleteRule(sheetObj.cssRules.length-1); }
// and re-enable whole page printing
disableSheet(0,true);
}
다른 한 가지 작업은 인쇄 스타일이 처음에 비활성화되어 전체 페이지 인쇄가 가능하도록 한 줄을 onload 처리에 추가하는 것입니다.
<body onLoad='disableSheet(0,true)'>
그런 다음 문서의 어느 곳에서나 div를 인쇄 할 수 있습니다. 버튼 등으로 printDiv ( "thedivid")를 발행하십시오.
이 방법의 큰 장점은 페이지 내에서 선택한 내용을 인쇄하는 일반적인 솔루션을 제공합니다. 포함하는 div를 포함하여 인쇄되는 요소에 기존 스타일을 사용할 수도 있습니다.
참고 : 내 구현에서 이것은 첫 번째 스타일 시트 여야합니다. 나중에 시트 순서에서 확인해야하는 경우 시트 참조 (0)를 적절한 시트 번호로 변경하십시오.
@Kevin Florida 같은 클래스의 여러 div가있는 경우 다음과 같이 사용할 수 있습니다.
<div style="display:none">
<div id="modal-2" class="printableArea">
<input type="button" class="printdiv-btn" value="print a div!" />
</div>
</div>
Colorbox 내부 콘텐츠 형식을 사용하고있었습니다
$(document).on('click', '.printdiv-btn', function(e) {
e.preventDefault();
var $this = $(this);
var originalContent = $('body').html();
var printArea = $this.parents('.printableArea').html();
$('body').html(printArea);
window.print();
$('body').html(originalContent);
});
내 경우에는 페이지 안에 이미지를 인쇄해야했습니다. 내가 투표 한 솔루션을 사용할 때 빈 페이지가 1 개 있었고 다른 페이지에 이미지가 표시되었습니다. 누군가에게 도움이되기를 바랍니다.
내가 사용한 CSS는 다음과 같습니다.
@media print {
body * {
visibility: hidden;
}
#not-print * {
display: none;
}
#to-print, #to-print * {
visibility: visible;
}
#to-print {
display: block !important;
position: absolute;
left: 0;
top: 0;
width: auto;
height: 99%;
}
}
내 HTML은 다음과 같습니다
<div id="not-print" >
<header class="row wrapper page-heading">
</header>
<div class="wrapper wrapper-content">
<%= image_tag @qrcode.image_url, size: "250x250" , alt: "#{@qrcode.name}" %>
</div>
</div>
<div id="to-print" style="display: none;">
<%= image_tag @qrcode.image_url, size: "300x300" , alt: "#{@qrcode.name}" %>
</div>
인쇄를 위해 특별한 스타일 시트를 사용하십시오
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
인쇄하고 싶지 않은 모든 태그에 "noprint"클래스를 추가하십시오.
CSS에서
.noprint {
display: none;
}
이 div 만 인쇄하려면 다음 지침을 사용해야합니다.
@media print{
*{display:none;}
#mydiv{display:block;}
}
printDiv () 함수가 몇 번 나왔지만이 경우 모든 바인딩 요소와 입력 값이 느슨해집니다. 그래서 내 해결책은 "body_allin"이라는 모든 것과 div의 첫 번째 "body_print"외부에 대한 div를 만드는 것입니다.
그런 다음이 함수를 호출하십시오.
function printDiv(divName){
var printContents = document.getElementById(divName).innerHTML;
document.getElementById("body_print").innerHTML = printContents;
document.getElementById("body_allin").style.display = "none";
document.getElementById("body_print").style.display = "";
window.print();
document.getElementById("body_print").innerHTML = "";
document.getElementById("body_allin").style.display = "";
document.getElementById("body_print").style.display = "none";
}
ID가 "printarea"인 콘텐츠를 제외한 다른 모든 콘텐츠를 비활성화하는 별도의 CSS 스타일을 사용할 수 있습니다.
자세한 설명과 예제는 CSS 디자인 : 인쇄 예정을 참조하십시오 .
나는 각각 버튼으로 여러 이미지를 가지고 있었고 각 div를 이미지로 인쇄하려면 버튼을 클릭해야했습니다. 이 솔루션은 브라우저에서 캐시를 사용 중지 한 경우 Chrome에서 이미지 크기가 변경되지 않는 경우 작동합니다.
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
return true;
}
<div id="printableArea">
<h1>Print me</h1>
</div>
<input type="button" onclick="printDiv('printableArea')" value="print a div!" />
현재 페이지에 영향을 미치지 않고 한 번 더 접근하고 인쇄하는 동안 CSS를 유지합니다. 여기서 선택기는 인쇄해야 할 내용을 특정 div 선택기 여야합니다.
printWindow(selector, title) {
var divContents = $(selector).html();
var $cssLink = $('link');
var printWindow = window.open('', '', 'height=' + window.outerHeight * 0.6 + ', width=' + window.outerWidth * 0.6);
printWindow.document.write('<html><head><h2><b><title>' + title + '</title></b></h2>');
for(var i = 0; i<$cssLink.length; i++) {
printWindow.document.write($cssLink[i].outerHTML);
}
printWindow.document.write('</head><body >');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.onload = function () {
printWindow.focus();
setTimeout( function () {
printWindow.print();
printWindow.close();
}, 100);
}
}
여기에 외부 CSS가 적용되는 시간 초과 표시가 제공되었습니다.
공간이 비어있는 높이에 가장 적합한 CSS :
@media print {
body * {
visibility: hidden;
height:0;
}
#section-to-print, #section-to-print * {
visibility: visible;
height:auto;
}
#section-to-print {
position: absolute;
left: 0;
top: 0;
}
}
제공된 많은 솔루션을 시도했지만 그중 아무것도 완벽하게 작동하지 않았습니다. CSS 또는 JavaScript 바인딩이 손실됩니다. CSS와 JavaScript 바인딩을 잃지 않는 완벽하고 쉬운 솔루션을 찾았습니다.
HTML :
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
<input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p>
자바 스크립트 :
function printFunc() {
var divToPrint = document.getElementById('printarea');
var htmlToPrint = '' +
'<style type="text/css">' +
'table th, table td {' +
'border:1px solid #000;' +
'padding;0.5em;' +
'}' +
'</style>';
htmlToPrint += divToPrint.outerHTML;
newWin = window.open("");
newWin.document.write("<h3 align='center'>Print Page</h3>");
newWin.document.write(htmlToPrint);
newWin.print();
newWin.close();
}
나는이 파티에 늦었지만 또 다른 접근 방식을 제안하고 싶습니다. 웹 페이지의 일부를 동적으로 인쇄하기 위해 PrintElements 라는 작은 JavaScript 모듈을 작성했습니다 .
선택한 노드 요소를 반복하여 작동하며 각 노드마다 BODY 요소까지 DOM 트리를 통과합니다. 초기 레벨 (인쇄 할 노드의 레벨)을 포함하여 각 레벨에서 마커 클래스 ( pe-preserve-print
)를 현재 노드에 연결합니다. 그런 다음 다른 마커 클래스 ( pe-no-print
)를 현재 노드의 모든 형제에 연결하지만 pe-preserve-print
클래스 가없는 경우에만 해당 합니다. 세 번째로, 그것은 또한 다른 조상을 보존 된 조상 요소에 연결 pe-preserve-ancestor
합니다.
간단한 간단한 보충 인쇄 전용 CSS는 각 요소를 숨기고 표시합니다. 이 방법의 장점은 모든 스타일이 유지되고 새 창을 열지 않으며 많은 DOM 요소를 이동할 필요가 없으며 일반적으로 원본 문서에 비 침습적이라는 것입니다.
자세한 내용은 데모를 참조 하거나 관련 기사 를 읽으십시오 .
이것을 사용할 수 있습니다 : http://vikku.info/codesnippets/javascript/print-div-content-print-only-the-content-of-an-html-element-and-not-the-whole-document/
사용 또는 visibility:visible
과 visibility:hidden
함께 CSS 속성@media print{}
'display : none'은 중첩 된 모든 'display : block'을 숨 깁니다. 그것은 해결책이 아닙니다.
해결책을 찾았습니다.
@media print {
.print-area {
background-color: white;
height: 100%;
width: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index:1500;
visibility: visible;
}
@page{
size: portrait;
margin: 1cm;
}
/*IF print-area parent element is position:absolute*/
.ui-dialog,
.ui-dialog .ui-dialog-content{
position:unset !important;
visibility: hidden;
}
}
참고 URL : https://stackoverflow.com/questions/468881/print-div-id-printarea-div-only
'Programing' 카테고리의 다른 글
C ++에서 문자열을 어떻게 토큰 화합니까? (0) | 2020.02.22 |
---|---|
HttpClient의 인증 헤더 설정 (0) | 2020.02.22 |
파이썬에서 디렉토리의 zip 아카이브를 만드는 방법은 무엇입니까? (0) | 2020.02.22 |
키 저장소 인증서의 SHA-1 지문 (0) | 2020.02.22 |
HTML 스크래핑 옵션? (0) | 2020.02.22 |