JavaScript 또는 jquery를 사용하여 HTML 페이지를 PDF로 저장할 수 있습니까?
JavaScript 또는 jquery를 사용하여 HTML 페이지를 PDF로 저장할 수 있습니까?
상세히:
테이블이 포함 된 HTML 페이지를 생성했습니다. 'PDF로 저장'버튼이 하나 있습니다. 사용자가 해당 버튼을 클릭하면 해당 HTML 페이지가 PDF 파일로 변환되어야합니다.
JavaScript 또는 jquery를 사용할 수 있습니까?
예 , jspdf 를 사용하여 pdf 파일을 만듭니다.
그런 다음이를 데이터 URI로 변환하고 다운로드 링크를 DOM에 삽입 할 수 있습니다.
그러나 HTML에서 pdf 로의 변환을 직접 작성해야합니다.
페이지의 인쇄용 버전을 사용하고 사용자가 페이지를 인쇄 할 방법을 선택하도록합니다.
편집 : 분명히 최소한의 지원이 있습니다
따라서 대답은 자신의 PDF 작성기를 작성하거나 기존 PDF 작성기를 사용하여 서버에서 수행하는 것입니다.
야 자바 스크립트로 매우 쉽습니다. 이 코드가 유용하기를 바랍니다.
JSpdf 라이브러리 가 필요합니다 .
<div id="content">
<h3>Hello, this is a H3 tag</h3>
<p>a pararaph</p>
</div>
<div id="editor"></div>
<button id="cmd">Generate PDF</button>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
'#editor': function (element, renderer) {
return true;
}
};
$('#cmd').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
// This code is collected but useful, click below to jsfiddle link.
</script>
내가 어떻게 할 것인지는 방탄 디자인이 아닌 아이디어입니다. 수정해야합니다.
- 사용자가 PDF로 저장 버튼을 클릭합니다.
- 서버는 ajax를 사용하여 호출을 보냅니다.
- 서버는 HTML을 사용하여 생성 된 PDF의 URL로 응답하며 Apache FOP를 매우 성공적으로 사용했습니다.
- ajax 응답을 처리하는 js는 js가 보내는 URL을 가리 키기 위해 location.href를 수행하고 해당 URL이로드되는 즉시 콘텐츠 처리 헤더를 첨부 파일로 사용하여 사용자가 파일을 다운로드하도록합니다.
Phantomjs를 사용할 수 있습니다. 여기에서 다운로드 하고 다음 예제를 사용하여 html-> pdf 변환 기능 https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js 를 테스트 하십시오.
예제 코드 :
phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf
이것은 늦은 답변 일 수 있지만 이것이 가장 좋습니다 : https://github.com/eKoopmans/html2pdf
순수한 자바 스크립트 구현. ID로 단일 요소 만 지정하고 변환 할 수 있습니다.
내가 사용 jsPDF
하고 dom-to-image
도서관 PDF로 수출 HTML에.
나는 누구의 관심사에 대한 언급으로 여기에 게시합니다.
$('#downloadPDF').click(function () {
domtoimage.toPng(document.getElementById('content2'))
.then(function (blob) {
var pdf = new jsPDF('l', 'pt', [$('#content2').width(), $('#content2').height()]);
pdf.addImage(blob, 'PNG', 0, 0, $('#content2').width(), $('#content2').height());
pdf.save("test.pdf");
});
});
데모 : https://jsfiddle.net/viethien/md03wb21/27/
요컨대 : 아니요. 첫 번째 문제는 대부분의 브라우저에서 보안상의 이유로 기본적으로 no로 설정되어있는 파일 시스템에 대한 액세스입니다. 최신 브라우저는 때때로 데이터베이스 형태로 최소한의 저장소를 지원하거나 사용자에게 파일 액세스를 활성화하도록 요청할 수 있습니다.
파일 시스템에 액세스 할 수있는 경우 HTML로 저장하는 것은 그리 어렵지 않습니다 (JS 문서의 파일 객체 참조). PDF는 그렇게 쉽지 않습니다. PDF는 Javascript에 실제로 적합하지 않은 고급 파일 형식입니다. Javascript에서 직접 지원하지 않는 데이터 유형 (예 : 단어 및 쿼드)으로 정보를 작성해야합니다. 또한 파일에 저장해야하는 사전 조회 시스템을 미리 정의해야합니다. 누군가가 그것을 작동시킬 수 있다고 확신하지만, 관련된 노력과 시간은 C ++ 또는 Delphi를 배우는 데 더 낫습니다.
그러나 사용자가 제한되지 않은 액세스를 제공하면 HTML 내보내기가 가능해야합니다.
$('#cmd2').click(function() {
var options = {
//'width': 800,
};
var pdf = new jsPDF('p', 'pt', 'a4');
pdf.addHTML($("#content2"), -1, 220, options, function() {
pdf.save('admit_card.pdf');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<div id="content2" style="background: #fff;border-bottom: 1px solid #ffffff;">
<div class="tokenDet" style="padding: 15px;border: 1px solid #000;width: 80%;margin: 0 auto;position: relative;overflow: hidden;">
<div class="title" style="text-align: center;border-bottom: 1px solid #000;margin-bottom: 15px;">
<h2>Entrance Exam Hall Ticket</h2>
</div>
<div class="parentdiv" style="display: inline-block;width: 100%;position: relative;">
<div class="innerdiv" style="width: 80%;float: left;">
<div class="restDet">
<div class="div">
<div class="label" style="width: 30%;float: left;">
<strong>Name</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>Santanu Patra</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>D.O.B.</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>17th April, 1995</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Address</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>P.S. Srijan Corporate Park, Saltlake, Sector 5, Kolkata-91</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Contact Number</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>9874563210</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Email Id</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>santanu@macallied.com</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Parent(s) Name</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>S. Patra</span><br /><span>7896541230</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Exam Center</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>Institute of Engineering & Management</span>
</div>
<div class="label" style="width: 30%;float: left;">
<strong>Hall Number</strong>
</div>
<div class="data" style="width: 70%;display: inline-block;">
<span>COM-32</span>
</div>
</div>
</div>
</div>
<div class="sideDiv" style="width: 20%;float: left;">
<div class="atts" style="float: left;width: 100%;">
<div class="photo" style="width: 115px;height: 150px;float: right;">
<img src="images/candidateImg.gif" style="width: 100%;"/>
</div>
<div class="sign" style="position: absolute;bottom: 0;right: 0;border-top: 1px dashed #000;left: 80%;text-align: right;">
<small>Self Attested</small>
</div>
</div>
</div>
</div>
</div>
</div>
<button class="btn btn-info" id="cmd2">Download Token</button>
JavaScript를 사용하여 HTML을 PDf로 변환하는 또 다른 분명하고 쉬운 방법이 있습니다. 온라인 API를 사용하십시오. 사용자가 오프라인 일 때 변환을 수행 할 필요가 없으면 제대로 작동합니다.
FreeHtmlToPdf.com is one option that has a nice API. I'm sure you can find alternatives (like PdfMage which obviously has its own API but doesn't share its protocol).
For FreeHtmlToPdf API you'd have something like this:
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "http://freehtmltopdf.com");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "html");
hiddenField.setAttribute("value", "<html><body>Hi there!</body></html>");
form.appendChild(hiddenField);
hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "baseurl");
hiddenField.setAttribute("value", "http://localhost");
form.appendChild(hiddenField);
hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "convert");
hiddenField.setAttribute("value", "");
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
Yes. For example you can use the solution by https://grabz.it.
It's got a Javascript API which can be used in different ways to grab and manipulate the screenshot. In order to use it in your app you will need to first get an app key and secret and download the free Javascript SDK.
So, let's see a simple example for using it:
//first include the grabzit.min.js library in the web page
<script src="grabzit.min.js"></script>
//include the code below to add the screenshot to the body tag
<script>
//use secret key to sign in. replace the url.
GrabzIt("Sign in to view your Application Key").ConvertURL("http://www.google.com").Create();
</script>
Then simply wait a short while and the image will automatically appear at the bottom of the page, without you needing to reload the page.
That's the simplest one. For more examples with image manipulation, attaching screenshots to elements and etc check the documentation.
It is much easier and reliable to convert html to pdf server side. We are using Google Puppeteer. It is well maintained with wrappers for any server side language of your choosing. Puppeteer uses headless Chrome to generate screenshots and/or PDF files. It will save you a LOT of headache especially if you need to generate complex PDF files with tables, images, graphs, multiple pages and so
https://developers.google.com/web/tools/puppeteer/
I think No because JavaScript can't write to disk you should send the page to the server and generate the pdf file then the client will download it
'Nice programing' 카테고리의 다른 글
C #에서 SQL 코드 구문 분석 (0) | 2020.11.15 |
---|---|
null을 사전의 키로 사용할 수없는 이유 (0) | 2020.11.15 |
T-SQL을 사용한 퍼지 매칭 (0) | 2020.11.15 |
엄격 모드가 더 성능이 좋습니까? (0) | 2020.11.15 |
MVC에서 거대한 컨트롤러 또는 많은 컨트롤러를 갖는 것이 더 낫습니까? (0) | 2020.11.15 |