Using PDF-Lib to create a document and print without saving the document locally

Within my web application, I am attempting to create a PDF document (which I am doing successfully) and then print it.

Most of the solutions I have found said that you will have to do it server-side probably with some PHP, which would be fine. but If I did that, I would have no clue how to do this.

The application is only really used by one machine and it is not distributed on the web so it is locally hosted only so no need for another end-user computer.


Application Goal / Expected result

I would like the application to:

  • Generate a PDF based on the user’s input (DONE AND WORKS)
  • Use the PDF and PRINT straight away

So it appears I would have a few viable options…

  • PDF-Lib client-side only (possible client-side DB?)
  • PDF-Lib client-side and a server-side link using PHP?
  • Fully server-side
  • A base 64 link?

I have tried locally saving it to the machine and using the file but it will not allow me, unfortunately 🙁

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Your Certificate for The Event</title>
    <link rel="stylesheet" href="style.css">
    <link rel="favicon" href="favicon.ico">
</head>

<body>
    <header>
        <img src="FR_Logo.png" alt="FRSystems Logo" width="500" height="250" />
        <h4>Get your certificate of your laps</h4>

    </header>
    <main>

        <label for="name">Type Your Name</label>
        <input required type="text" name="Name" autocomplete="name" placeholder="" id="name" minlength="1"
               maxlength="16">
        <Button id="submitBtn">Get Certificate</Button>


    </main>

    <script src="https://unpkg.com/pdf-lib/dist/pdf-lib.js"></script>
    <script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"></script>
    <iframe id="iframe"></iframe>

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

</html>

Index.JS

const userName = document.getElementById("name");
const submitBtn = document.getElementById("submitBtn");

const { PDFDocument, rgb, degrees, StandardFonts } = PDFLib;


const capitalize = (str, lower = false) =>
  (lower ? str.toLowerCase() : str).replace(/(?:^|s|["'([{])+S/g, (match) =>
    match.toUpperCase()
  );

submitBtn.addEventListener("click", () => {
  const val = capitalize(userName.value);

  //check if the text is empty or not
  if (val.trim() !== "" && userName.checkValidity()) {
    console.log(val);
    createPdf(val);
  } else {
    userName.reportValidity();
  }
});

function print() {
    var frame = document.getElementById('frame');
    frame.contentWindow.focus();
    frame.contentWindow.print();
};


function readURL(input) {
    console.log("GOT HERE");
//    if (input.files && input.files[0]) {
    console.log("GOT HERE 2");
    var reader = new FileReader();

    reader.onload = function (e) {
        console.log(e.target.result);
//            $('#pdfResult')
//                .attr('src', e.target.result);
    };
    reader.readAsDataURL(input.files[0]);
    console.log(reader.readAsDataURL(input.files[0]));

//    }
};

async function createPdf(val) {
    const pdfDoc = await PDFDocument.create();
    const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman);

    const page = pdfDoc.addPage();
    const { width, height } = page.getSize();
    page.setSize(841.89, 595.28)
    // midpoint x = 420.945, y= 297.64

    console.log(page.getSize(),width,height)
    const fontSize = 30
    var textWidth = timesRomanFont.widthOfTextAtSize(val, fontSize);
    console.log(timesRomanFont.widthOfTextAtSize(val, fontSize))
    var textHeight = timesRomanFont.heightAtSize(fontSize);
    var nameY = ((page.getHeight() / 2) + 50) - (textHeight / 2);
    var centerY = page.getHeight() / 2 - textHeight / 2;
    var centerX = page.getWidth() / 2 - textWidth / 2;

    page.drawText(val, {
        x: centerX,
        y: nameY,
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0, 0),
    });

    var score = "32"; // Would be taken from the database (Select query) using ID/ChipNumber
    var scoreString = "who completed " + score + " laps";
    var bottomText = "< EVENT NAME > on < LONG DATE >";
    var supportingText = "< Support Text >"

    var textWidthScoreString = timesRomanFont.widthOfTextAtSize(scoreString, fontSize);
    console.log(timesRomanFont.widthOfTextAtSize(scoreString, fontSize));
    var scoreY = ((page.getHeight() / 2) + 0) - (textHeight / 2);
    var scoreX = page.getWidth() / 2 - textWidthScoreString / 2;

    var bottomTextWidthString = timesRomanFont.widthOfTextAtSize(bottomText, fontSize);
    var bottomTextY = ((page.getHeight() / 2) - 50) - (textHeight / 2);
    var bottomTextX = page.getWidth() / 2 - bottomTextWidthString / 2;


    var supportingTextWidthString = timesRomanFont.widthOfTextAtSize(supportingText, fontSize);
    var supportingTextY = ((page.getHeight() / 2) - 100) - (textHeight / 2);
    var supportingTextX = page.getWidth() / 2 - supportingTextWidthString / 2;


    page.drawText(scoreString, {
        x: scoreX,
        y: scoreY,
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0, 0),
    });

    page.drawText(bottomText, {
        x: bottomTextX,
        y: bottomTextY,
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0, 0),
    });

    page.drawText(supportingText, {
        x: supportingTextX,
        y: supportingTextY,
        size: fontSize,
        font: timesRomanFont,
        color: rgb(0, 0, 0),
    });


    const pdfBytes = await pdfDoc.save();

    console.log(pdfBytes);
    console.log(pdfDoc)

    // Create a new file
    // This uses File Saver to save the files, i used this to temp save whilst i moved around the text
    var file = new File(
        [pdfBytes],
        "test-Certificate.pdf",
        {
            type: "application/pdf;charset=utf-8",
        }
    );
    console.log(file);





//    var iframe = document.getElementById('iframe');
//    iframe.src = file;
//    iframe.contentWindow.focus();
//    iframe.contentWindow.print();
//    readURL(file);
//    saveAs(file);
    console.log(saveAs(file));

};