I am not a hardcore javascript user. I am trying to edit a pdf and add additional information. For that I am using PDF-LIB (or I am trying to). In the example code on their github page. They are using a await fetch() method that then returns a arrayBuffer.
It needs to run in a local envirement without the need to install several dependencies or big packages.
When I exactly copy their code everything works. I fetch the pdf from a cors allowed example pdf and no issue.
But when I change the code to get a pdf from my assets folder the arrayBuffer stays empty. What is diffrent with fetching localy or on the same server then getting it from their host?
<!-- https://github.com/Hopding/pdf-lib -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>pdf-lib test</title>
<link rel="stylesheet" href="./assets/css/main.css">
<script src="./assets/js/pdf-lib.js"></script>
<script src="./assets/js/download.js"></script>
</head>
<body>
<div>
<p>Click the button to modify an existing PDF document with <code>pdf-lib</code></p>
<button onclick="modifyPdf()">Modify PDF</button>
<p class="small">(Your browser will download the resulting file)</p>
</div>
</body>
<script>
const { degrees, PDFDocument, StandardFonts, rgb } = PDFLib
async function modifyPdf() {
// Fetch an existing PDF document
// const url = 'http://127.0.0.1:5500/assets/base/with_update_sections.pdf'
// const url = './assets/base/with_update_sections.pdf'
const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())
console.log(existingPdfBytes)
// // Load a PDFDocument from the existing PDF bytes
// const pdfDoc = await PDFDocument.load(existingPdfBytes)
// // Embed the Helvetica font
// const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)
// // Get the first page of the document
// const pages = pdfDoc.getPages()
// const firstPage = pages[0]
// // Get the width and height of the first page
// const { width, height } = firstPage.getSize()
// // Draw a string of text diagonally across the first page
// firstPage.drawText('This text was added with JavaScript!', {
// x: 5,
// y: height / 2 + 300,
// size: 50,
// font: helveticaFont,
// color: rgb(0.95, 0.1, 0.1),
// rotate: degrees(-45),
// })
// // Serialize the PDFDocument to bytes (a Uint8Array)
// const pdfBytes = await pdfDoc.save()
// // Trigger the browser to download the PDF document
// // download(pdfBytes, "pdf-lib_modification_example.pdf", "application/pdf");
// download(pdfBytes, "with_update_sections.pdf", "application/pdf");
}
</script>
</html>