Embed PDF Pages (pdf-lib)
Embed PDF pages with pdf-lib.
by Rapha Souza
HTML
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<p>Click the button to embed PDF pages with <code>pdf-lib</code></p>
<button onclick="embedPdfPages()">Create PDF</button>
<p class="small">(Your browser will download the resulting file)</p>
</body>
<script>
const { PDFDocument } = PDFLib
async function embedPdfPages() {
// Fetch American flag PDF
const flagUrl = 'https://pdf-lib.js.org/assets/american_flag.pdf';
const flagPdfBytes = await fetch(flagUrl).then((res) => res.arrayBuffer());
// Fetch U.S. constitution PDF
const constitutionUrl = 'https://pdf-lib.js.org/assets/us_constitution.pdf';
const constitutionPdfBytes = await fetch(constitutionUrl).then((res) =>
res.arrayBuffer(),
);
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create();
// Embed the first page of the American flag PDF
const [americanFlag] = await pdfDoc.embedPdf(flagPdfBytes);
// Load the constitution PDF into a PDFDocument
const usConstitutionPdf = await PDFDocument.load(constitutionPdfBytes);
// Embed the second page of the constitution and clip the preamble
const preamble = await pdfDoc.embedPage(usConstitutionPdf.getPages()[1], {
left: 55,
bottom: 485,
right: 300,
top: 575,
});
// Get the width/height of the American flag PDF scaled down to 30% of its original size
const americanFlagDims = americanFlag.scale(0.3);
// Get the width/height of the preamble clipping scaled up to 225% of its original size
const preambleDims = preamble.scale(2.25);
// Add a blank page to the document
const page = pdfDoc.addPage();
// Draw the American flag image in the center top of the page
page.drawPage(americanFlag, {
...americanFlagDims,
x:...
CSS
body {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
p {
font-family: helvetica;
font-size: 24px;
text-align: center;
margin: 25px;
}
.small {
font-family: helvetica;
font-size: 18px;
text-align: center;
margin: 25px;
}
button {
background-color: #008CBA;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
font-size: 16px;
}