Skip to content

Instantly share code, notes, and snippets.

@MattHealy
Created July 30, 2024 09:52
Show Gist options
  • Save MattHealy/b13900fb62a245dafd7c92a6b69f75c3 to your computer and use it in GitHub Desktop.
Save MattHealy/b13900fb62a245dafd7c92a6b69f75c3 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jsPDF Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
</head>
<body>
<button id="generatePDF">Generate PDF</button>
<script>
document.getElementById('generatePDF').addEventListener('click', function () {
const { jsPDF } = window.jspdf;
const pdf = new jsPDF();
const imgUrl = 'https://propertyphotos.vaultre.com.au/3080/small.63351809__1675908074-27830-coronis-rental-21044143-1659930321G0dwNu.jpg';
const img = new Image();
img.src = imgUrl;
img.onload = function() {
// Scale image to fit within the PDF dimensions
const imgWidth = img.width;
const imgHeight = img.height;
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
const scaledWidth = imgWidth * ratio;
const scaledHeight = imgHeight * ratio;
// Center the image in the PDF
const x = (pdfWidth - scaledWidth) / 2;
const y = (pdfHeight - scaledHeight) / 2;
pdf.addImage(img, 'JPEG', x, y, scaledWidth, scaledHeight);
pdf.save('image.pdf');
};
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment