const { PDFDocument, rgb } = PDFLib
async function addAttachments()
{
// Define attachment URLs
const jpgUrl = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg',
pdfUrl = 'https://pdf-lib.js.org/assets/us_constitution.pdf',
// Fetch attachments
jpgAttachmentBytes = await fetch(jpgUrl).then(res => res.arrayBuffer()),
pdfAttachmentBytes = await fetch(pdfUrl).then(res => res.arrayBuffer()),
pdfDoc = await PDFDocument.create();
// Add the JPG attachment
await pdfDoc.attach(jpgAttachmentBytes, 'cat_riding_unicorn.jpg',
{
mimeType: 'image/jpeg',
description: 'Cool cat riding a unicorn!',
creationDate: new Date('2019/12/01'),
modificationDate: new Date('2020/04/19')
});
// Add the PDF attachment
await pdfDoc.attach(pdfAttachmentBytes, 'us_constitution.pdf',
{
mimeType: 'application/pdf',
description: 'Constitution of the United States',
creationDate: new Date('1787/09/17'),
modificationDate: new Date('1992/05/07')
});
// Add a page with some text
const page = pdfDoc.addPage();
page.drawText('This PDF has two attachments. Note that only some appropriated PDF readers can view attachments. For example the Adobe Reader.', {x: 135, y: 415});
// Serialize the PDFDocument to bytes (a Uint8Array)
const pdfBytes = await pdfDoc.save();
// Trigger the browser to download the PDF document
download(pdfBytes, "pdf-lib_add_attachments.pdf", "application/pdf");
}
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;
}
blockquote
{
background-color: rgba(255,229,100,.3);
border-left: 8px solid #ffe564;
padding: 15px 30px 15px 15px;
}
<script src="https://unpkg.com/pdf-lib@1.7.0"></script>
<script src="https://unpkg.com/downloadjs@1.4.7"></script>
<br><br><br>
<p>Click the button below to create a document and attach a JPEG image and PDF file with <code>pdf-lib</code></p>
<blockquote>Note that only some PDF readers can view attachments. This includes Adobe Reader, Foxit Reader, and Firefox.</blockquote>
<button onclick="addAttachments()">Create PDF</button>
<p class="small">(Your browser will download the resulting file)</p>