Home > Software design >  File PDF not showing in iframe with javascript dataUri docoument.querySelector
File PDF not showing in iframe with javascript dataUri docoument.querySelector

Time:12-30

I have a project to display pdf file data in iframe with dataUri, but it's not showing. Please help me

File Index.php

<iframe src="" id="iframe" ></iframe>
<input required type="text" name="Name" id="name" minlength="3" maxlength="16">

<script src="https://unpkg.com/[email protected]"></script>
<script src="https://unpkg.com/@pdf-lib/[email protected]"></script>
<script src="./index.js"></script>

enter image description here

What's wrong with my project?

CodePudding user response:

Please provide code snippets in formatted text instead of screenshots, it will help people answer your question more rapidly.

I suspect that there could be a problem during PDF generation, according to the PDF-LIB (https://pdf-lib.js.org) example documentation, you should use:

 const { PDFDocument, StandardFonts, rgb } = PDFLib 

with a global scope. In the meantime, different browsers and web servers might have different policies about iframe embedding and base64 encoding for pdf files.

The folowing snipets work for me on Firefox:

<html>
    <head>
        <script src="https://unpkg.com/[email protected]"></script>
        <script src="https://unpkg.com/@pdf-lib/[email protected]"></script>
    </head>
    <body>
        <iframe src="" id="iframe" ></iframe>
    <script src="./pdf.js"> </script>
  </body>
</html>

pdf.js

const { PDFDocument, StandardFonts, rgb } = PDFLib
async function generatePdf() {
    // Create a new PDFDocument
    const pdfDoc = await PDFDocument.create()
    // Embed the Times Roman font
    const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman)
    // Add a blank page to the document
    const page = pdfDoc.addPage()
    // Get the width and height of the page
    const { width, height } = page.getSize()
    // Draw a string of text toward the top of the page
    const fontSize = 30
    page.drawText('Creating PDFs in JavaScript is awesome!', {
        x: 50,
        y: height - 4 * fontSize, 
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0.53, 0.71), })
        // Serialize the PDFDocument to bytes (a Uint8Array)
        const pdfBytes = await pdfDoc.save()
        const Uri = await pdfDoc.saveAsBase64({ dataUri: true });
        document.querySelector("#iframe").src = Uri;
    }
generatePdf();
  • Related