get_pdf というクラスのボタンを押下したら、現在表示中のWebページのスクリーンショットが PDF で保存されます。
jQuery(function($) {
$('.get_pdf').on('click', () => {
// コンテンツの横幅
let document_width = $(document).width();
document_width = document_width * window.devicePixelRatio;
// コンテンツの高さ
let document_height = $(document).height() * window.devicePixelRatio;
// jsPDF のインスタンス
const pdf = new jsPDF('l', 'pt', 'a4', false);
// pdfの横幅
const pdf_width = pdf.internal.pageSize.width;
// pdfの高さ
const pdf_height = pdf.internal.pageSize.height;
// 必要なページ数
const pdf_pages = Math.ceil((document_height * (pdf_width / document_width)) / pdf_height);
html2canvas(document.querySelector("body")).then(canvas => {
// オリジナルのカンバスを残しておく
const canvas_org = canvas;
for (let i = 0; i < pdf_pages; i++) {
let canvas_new;
const cropper = document.createElement('canvas').getContext('2d');
// 切り抜くカンバスのサイズ
const crop_height = pdf_height * (document_width / pdf_width);
cropper.canvas.width = document_width;
cropper.canvas.height = crop_height * (i + 1);
// カンバスの切り抜き
cropper.drawImage(canvas_org, 0, crop_height * i * -1);
canvas_new = cropper.canvas;
// 最初以外は addPage() を実行する
if (i > 0)
pdf.addPage();
// カンバスを追加する
pdf.addImage(canvas_new, 'JPEG', 0, 0, pdf_width, 0);
// ページを追加する
pdf.setPage(i + 1);
// 最後に保存して開く
if (pdf_pages === i + 1) {
pdf.save('test.pdf');
window.open(pdf.output('bloburl'), '_blank');
}
}
});
});
});
window.jsPDF = window.jspdf.jsPDF;


