Created
November 11, 2023 05:13
-
-
Save adicahyaludin/d89e7a43d283ff6e6237c1132c69f052 to your computer and use it in GitHub Desktop.
capture web to pdf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const puppeteer = require('puppeteer'); | |
const { PDFDocument } = require('pdf-lib'); | |
const fs = require('fs'); | |
(async () => { | |
const url = 'https://orangerdev.space/cv-style-1/'; | |
// Membuka browser dan halaman baru | |
const browser = await puppeteer.launch({ | |
args: ['--disable-web-security'] | |
}); | |
const page = await browser.newPage(); | |
// Mengatur ukuran viewport sesuai dengan yang diminta | |
await page.setViewport({ width: 1140, height: 1080 }); | |
// Navigasi ke halaman yang dimaksud | |
await page.goto(url, { waitUntil: 'networkidle2', timeout: 60000 }); // Mengatur batas waktu menjadi 60 detik | |
// Scroll halaman hingga bawah untuk memicu animasi JavaScript | |
await page.evaluate(async () => { | |
await new Promise((resolve, reject) => { | |
var totalHeight = 0; | |
var distance = 100; | |
var timer = setInterval(() => { | |
var scrollHeight = document.body.scrollHeight; | |
window.scrollBy(0, distance); | |
totalHeight += distance; | |
if (totalHeight >= scrollHeight) { | |
clearInterval(timer); | |
resolve(); | |
} | |
}, 100); | |
}); | |
}); | |
// Tunggu beberapa detik setelah scroll untuk memastikan semua animasi selesai | |
await page.waitForTimeout(5000); | |
// Ambil screenshot dari halaman web | |
const imagePath = 'screenshot.png'; | |
await page.screenshot({ | |
path: imagePath, | |
fullPage: true | |
}); | |
// Membuat PDF dari gambar screenshot | |
const pdfDoc = await PDFDocument.create(); | |
const imageBytes = fs.readFileSync(imagePath); | |
const image = await pdfDoc.embedPng(imageBytes); | |
const a4Width = 595.28; | |
// Skala gambar agar lebarnya sesuai dengan lebar A4 | |
const scale = a4Width / image.width; | |
const imgWidth = a4Width; | |
const imgHeight = image.height * scale; | |
// Buat halaman dengan lebar A4 dan tinggi sesuai gambar yang disesuaikan | |
const pagePdf = pdfDoc.addPage([a4Width, imgHeight]); | |
pagePdf.drawImage(image, { | |
x: 0, // Mulai dari tepi kiri | |
y: imgHeight - image.height * scale, // Mulai dari tepi atas | |
width: imgWidth, | |
height: imgHeight | |
}); | |
const pdfBytes = await pdfDoc.save(); | |
fs.writeFileSync('cv.pdf', pdfBytes); | |
await browser.close(); | |
console.log("PDF berhasil di-generate dari screenshot!"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment