Trong bài viết "Hướng dẫn Convert HTML thành File PDF bằng JavaScript" , tôi sẽ trình bày cách tạo file PDF của từ một trang HTML với CSS bằng JavaScript và jQuery.Hướng dẫn Convert HTML thành File PDF bằng JavaScript" , tôi sẽ trình bày cách tạo file PDF của từ một trang HTML với CSS bằng JavaScript và jQuery.
Để thực hiện chúng ta sẽ sử dụng thư viên JS để chuyển đổi PDF:
- JSPDF.js
- html2canvas.js
Bước 1: Tạo một trang HTML để chuyển đổi HTMl sang PDF
Thêm bảng sau vào trang HTML của bạn.
Hello
a bit about this Project:
I will demonstrate how to generate PDF file of your HTML page with CSS using JavaScript and J query.
Company
Contact
Country
Alfreds Futterkiste
Maria Anders
Germany
Centro comercial Moctezuma
Francisco Chang
Mexico
Ernst Handel
Roland Mendel
Austria
Island Trading
Helen Bennett
UK
Laughing Bacchus Winecellars
Yoshi Tannamuri
Canada
Magazzini Alimentari Riuniti
Giovanni Rovelli
Italy
Bước 2: Thêm Style cho trang HTML này - Convert HTML To PDF
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child[even] {
background-color: #dddddd;
}
Bước 3: Thêm nút “Generate PDF ” - Convert HTML To PDF
Bước 4: Thêm thư viện sau vào trang HTML
Bước 5: Thêm đoạn code dưới để thực hiện Convert HTML To PDF
[function [] {
var
form = $['.form'],
cache_width = form.width[],
a4 = [595.28, 841.89]; // for a4 size paper width and height
$['#create_pdf'].on['click', function [] {
$['body'].scrollTop[0];
createPDF[];
}];
//create pdf
function createPDF[] {
getCanvas[].then[function [canvas] {
var
img = canvas.toDataURL["image/png"],
doc = new jsPDF[{
unit: 'px',
format: 'a4'
}];
doc.addImage[img, 'JPEG', 20, 20];
doc.save['Bhavdip-html-to-pdf.pdf'];
form.width[cache_width];
}];
}
// create canvas object
function getCanvas[] {
form.width[[a4[0] * 1.33333] - 80].css['max-width', 'none'];
return html2canvas[form, {
imageTimeout: 2000,
removeContainer: true
}];
}
}[]];
/*
* jQuery helper plugin for examples and tests
*/
[function [$] {
$.fn.html2canvas = function [options] {
var date = new Date[],
$message = null,
timeoutTimer = false,
timer = date.getTime[];
html2canvas.logging = options && options.logging;
html2canvas.Preload[this[0], $.extend[{
complete: function [images] {
var queue = html2canvas.Parse[this[0], images, options],
$canvas = $[html2canvas.Renderer[queue, options]],
finishTime = new Date[];
$canvas.css[{ position: 'absolute', left: 0, top: 0 }].appendTo[document.body];
$canvas.siblings[].toggle[];
$[window].click[function [] {
if [!$canvas.is[':visible']] {
$canvas.toggle[].siblings[].toggle[];
throwMessage["Canvas Render visible"];
} else {
$canvas.siblings[].toggle[];
$canvas.toggle[];
throwMessage["Canvas Render hidden"];
}
}];
throwMessage['Screenshot created in ' + [[finishTime.getTime[] - timer] / 1000] + " seconds
", 4000];
}
}, options]];
function throwMessage[msg, duration] {
window.clearTimeout[timeoutTimer];
timeoutTimer = window.setTimeout[function [] {
$message.fadeOut[function [] {
$message.remove[];
}];
}, duration || 2000];
if [$message]
$message.remove[];
$message = $[''].html[msg].css[{
margin: 0,
padding: 10,
background: "#000",
opacity: 0.7,
position: "fixed",
top: 10,
right: 10,
fontFamily: 'Tahoma',
color: '#fff',
fontSize: 12,
borderRadius: 12,
width: 'auto',
height: 'auto',
textAlign: 'center',
textDecoration: 'none'
}].hide[].fadeIn[].appendTo['body'];
}
};
}][jQuery];
Kết quả sẽ được như trang dưới:
Nhấp vào nút "Generatte PDF" và nhận tệp PDF như thế này.
Phần kết luận
Bạn có thể dễ dàng thêm chức năng Xuất sang PDF trong trang web mà không phụ thuộc phía máy chủ.
Chức năng tạo PDF có thể được nâng cao với các tùy chọn cấu hình jsPDF theo nhu cầu của bạn.
Cảm ơn bạn đã đọc !