JavaScript에서 직접 PDF 인쇄
HTML로 PDF 목록을 작성 중입니다. 목록에 다운로드 링크와 인쇄 버튼 / 링크를 포함하고 싶습니다. 사용자가 PDF를 보거나 PDF 뷰어를 열지 않고 PDF의 인쇄 대화 상자를 직접 열 수있는 방법이 있습니까?
PDF를 숨겨진 iframe으로 다운로드하고 JavaScript로 인쇄하도록 트리거하는 변형이 있습니까?
아래 설명에 따르면 최신 브라우저에서 더 이상 작동하지 않습니다.
이 질문은 도움이 될 수있는 접근 방식을 보여줍니다 . 포함 된 PDF를 자동 인쇄
<embed>
태그를 사용하여 문서에 PDF를 포함합니다.
<embed
type="application/pdf"
src="path_to_pdf_document.pdf"
id="pdfDocument"
width="100%"
height="100%" />
그런 다음 .print()
PDF가로드 될 때 Javascript의 요소에 대해 메소드 를 호출합니다 .
function printDocument(documentId) {
var doc = document.getElementById(documentId);
//Wait until PDF is ready to print
if (typeof doc.print === 'undefined') {
setTimeout(function(){printDocument(documentId);}, 1000);
} else {
doc.print();
}
}
임베드를 숨겨진 iframe에 배치하고 거기에서 인쇄하여 원활한 경험을 제공 할 수 있습니다.
다음은 iframe에서 PDF를 인쇄하는 기능입니다.
PDF의 URL을 함수에 전달하기 만하면됩니다. PDF가로드되면 iframe을 생성하고 인쇄를 트리거합니다.
이 함수는 iframe을 파괴하지 않습니다. 대신 함수가 호출 될 때마다 다시 사용합니다. 인쇄가 완료 될 때까지 필요하고 인쇄 메서드에는 콜백 지원이 없기 때문에 iframe을 파괴하기가 어렵습니다 (내가 아는 한).
printPdf = function (url) {
var iframe = this._printIframe;
if (!this._printIframe) {
iframe = this._printIframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function() {
setTimeout(function() {
iframe.focus();
iframe.contentWindow.print();
}, 1);
};
}
iframe.src = url;
}
http://printjs.crabbly.com/ 에서 Print.js를 다운로드 하십시오.
$http({
url: "",
method: "GET",
headers: {
"Content-type": "application/pdf"
},
responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
var pdfFile = new Blob([data], {
type: "application/pdf"
});
var pdfUrl = URL.createObjectURL(pdfFile);
//window.open(pdfUrl);
printJS(pdfUrl);
//var printwWindow = $window.open(pdfUrl);
//printwWindow.print();
}).error(function (data, status, headers, config) {
alert("Sorry, something went wrong")
});
https://github.com/mozilla/pdf.js/
라이브 데모 http://mozilla.github.io/pdf.js/
it's probably what you want, but I can't see the point of this since modern browsers include such functionality, also it will run terribly slow on low-powered devices like mobile devices that, by the way, have their own optimized plugins and apps.
I used this function to download pdf stream from server.
function printPdf(url) {
var iframe = document.createElement('iframe');
// iframe.id = 'pdfIframe'
iframe.className='pdfIframe'
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function () {
setTimeout(function () {
iframe.focus();
iframe.contentWindow.print();
URL.revokeObjectURL(url)
// document.body.removeChild(iframe)
}, 1);
};
iframe.src = url;
// URL.revokeObjectURL(url)
}
Cross browser solution for printing pdf from base64 string:
- Chrome: print window is opened
- FF: new tab with pdf is opened
- IE11: open/save prompt is opened
.
const blobPdfFromBase64String = base64String => {
const byteArray = Uint8Array.from(
atob(base64String)
.split('')
.map(char => char.charCodeAt(0))
);
return new Blob([byteArray], { type: 'application/pdf' });
};
const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // or however you want to check it
const printPDF = blob => {
try {
isIE11
? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
: printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
} catch (e) {
throw PDFError;
}
};
printPDF(blobPdfFromBase64String(base64String))
BONUS - Opening blob file in new tab for IE11
If you're able to do some preprocessing of the base64 string on the server you could expose it under some url and use the link in printJS
:)
참고URL : https://stackoverflow.com/questions/16239513/print-pdf-directly-from-javascript
'Nice programing' 카테고리의 다른 글
UPDLOCK, HOLDLOCK에 대해 혼란 스러움 (0) | 2020.10.05 |
---|---|
외부 앱이 영구 모델 (서버 데이터베이스)을 변경 한 경우 AngularJS가 뷰를 자동 업데이트 할 수 있습니까? (0) | 2020.10.05 |
AngularJS에서 격리 된 범위 지시문을 단위 테스트하는 방법 (0) | 2020.10.05 |
Chrome이 로컬 jQuery 쿠키를 무시하는 이유는 무엇입니까? (0) | 2020.10.05 |
내 git 'master'브랜치의 이름을 'release'로 어떻게 바꾸나요? (0) | 2020.10.05 |