How to use PDF-lib and how to center each line of texts on the page?

Joined
Aug 16, 2023
Messages
1
Reaction score
0
Hi,

I am very new to the html and javascript and I am trying to design a certificate in PDF. What I want to achieve is that when I click a button named 'Your Certificate', it will write the certificate in PDF file.

I have written some code to do this and my code can achieve what looks like below.
certificate.png


However, as you can see all the lines of texts are not center-aligned. Some lines are shifted to the left and some shifted to the right. I want all the lines of texts to be center-aligned on the page.

I am hoping to use methods such as 'widthOfString' and 'widthOfTextAtSize' but it seems that they both don't exist in my pdf-lib. How to fix this problem? I am new to the html and javascript and I don't know anything about node.js or npm which seems to be needed to use PDF-lib properly.

Below is my current code.
HTML:
<!DOCTYPE html>
<html>
<head>
    <title>Styled PDF Example</title>
</head>
<body>
    <button id="showcertificate">Your Certificate</button>

    <script>
        document.getElementById('showcertificate').addEventListener('click', async function() {
       
            // Import the pdf-lib library
            const { PDFDocument, rgb } = PDFLib;
            // Check if imported symbols are defined
            if (PDFDocument && rgb){
                // The import was successful
                console.log('pdf-lib has been successfully imported.');
            } else {
                // The import was not successful
                console.error('pdf-lib import failed.')
            }
           
            // Check if widthOfString method exists
            if (PDFDocument.prototype.widthOfString){
                console.log('widthOfString method exists in pdf-lib.');
            } else {
                console.log('widthOfString method does not exist in pdf-lib.');
            }

            // Check if widthOfTextAtSize method exists
            if (PDFDocument.prototype.widthOfTextAtSize) {
                console.log('widthOfTextAtSize method exists in pdf-lib.');
            } else {
                console.log('widthOfTextAtSize method does not exist in pdf-lib.');
            }

           

            // Create a new PDF document
            const pdfDoc = await PDFDocument.create();
            const page = pdfDoc.addPage([(297 / 25.4) * 96 * 0.7, (210 / 25.4) * 96 * 0.7]); // A4 landscape pageWidth = 786, pageHeight = 556
           

            // Add styled content to the page
            const titleText = 'CERTIFICATE OF COMPLETION';
            const subtitleText1 = 'This is to certify that';
            const nameText = 'name';
            const subtitleText2 = 'has completed the test';
            // get the current date
            const currentDate = new Date();
            const formattedDate = currentDate.toLocaleDateString();

            const textColor = rgb(0, 0, 0);
            const titleSize = 24;
            const subtitleSize = 16;
            const nameSize = 28;
            const dateSize = 16;

            // Get the width of the each text at the chosen size
            const titleWidth = titleText.length * (titleSize / 2);
            const subtitleWidth1 = subtitleText1.length * (subtitleSize / 2);
            const nameWidth = nameText.length * (nameSize / 2);
            const subtitleWidth2 = subtitleText2.length * (subtitleSize / 2);
            const dateWidth = formattedDate.length * (dateSize / 2);


            // Center the titleText horizontally
            const title = page.drawText(titleText, {
                x: (page.getWidth() - titleWidth) / 2,
                y: page.getHeight() - 100, // Added space from the top
                size: titleSize,
                color: textColor,
            });

            // Center the subtitleText1 horizontally
            const subtitle1 = page.drawText(subtitleText1, {
                x: (page.getWidth() - subtitleWidth1) / 2,
                y: page.getHeight() - 200, // Added space from the top
                size: subtitleSize,
                color: textColor,
            });

            // Center the nameText horizontally
            const name = page.drawText(nameText, {
                x: (page.getWidth() - nameWidth) / 2,
                y: page.getHeight() - 250, // Added space from the top
                size: nameSize,
                color: textColor,
            });

            // Center the subtitleText2 horizontally
            const subtitle2 = page.drawText(subtitleText2, {
                x: (page.getWidth() - subtitleWidth2) / 2,
                y: page.getHeight() - 300, // Added space from the top
                size: subtitleSize,
                color: textColor,
            });

            // Center the dateText horizontally
            const date = page.drawText(formattedDate, {
                x: (page.getWidth() - dateWidth) / 2,
                y: page.getHeight() - 350, // Added space from the top
                size: dateSize,
                color: textColor,
            });


            // Generate the PDF as a Uint8Array
            const pdfBytes = await pdfDoc.save();

            // Create a blob from the PDF data and create a URL
            const blob = new Blob([pdfBytes], { type: 'application/pdf' });
            const url = URL.createObjectURL(blob);

            // Open the PDF in a new tab
            window.open(url);
        });
    </script>
    <!-- Include the pdf-lib library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.16.0/pdf-lib.js"></script>
</body>
</html>
 
Joined
Jul 4, 2023
Messages
366
Reaction score
41
You can use widthOfTextAtSize from StandardFonts.

Proposed changes to the code

HTML:
<!DOCTYPE html>
<html>
  <head>
    <title>Styled PDF Example</title>
  </head>
  <body>
    <button id="showcertificate">Your Certificate</button>

    <!-- Include the pdf-lib library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf-lib/1.16.0/pdf-lib.js"></script>
    <script>
      document.querySelector('#showcertificate').onclick = async function() {
        const { PDFDocument, StandardFonts, rgb } = PDFLib;
        // Check if imported symbols are defined
        if (PDFDocument && StandardFonts && rgb)
          console.log('pdf-lib has been successfully imported.');
        else {
          console.error('pdf-lib import failed.');
          return false;
        }

        // Create a new PDF document
        const pdfDoc = await PDFDocument.create();
        const page = pdfDoc.addPage([786, 556]); // A4 landscape pageWidth = 786, pageHeight = 556

        const DOCUMENT_MARGIN_TOP = 100;
        const nameText = 'name';
        const currentDate = new Date(); // get the current date
        const font = await pdfDoc.embedFont(StandardFonts.Helvetica);

        const pdfTextLines = [
          { text:'CERTIFICATE OF COMPLETION', color:rgb(0,0,0), fontSize:24, marginTop:0 },
          { text:'This is to certify that', color:rgb(0,0,0), fontSize:16, marginTop:100 },
          { text:nameText, color:rgb(0,0,0), fontSize:28, marginTop:50 },
          { text:'has completed the test', color:rgb(0,0,0), fontSize:16, marginTop:50 },
          { text:currentDate.toLocaleDateString(), color:rgb(0,0,0), fontSize:16, marginTop:50 }
        ];

        let yCurrentLine = DOCUMENT_MARGIN_TOP;
        for (const textLine of pdfTextLines) {
          const textWidth = font.widthOfTextAtSize(textLine.text, textLine.fontSize);
          yCurrentLine += textLine.marginTop;

          const text = page.drawText(textLine.text, {
            x: (page.getWidth() / 2) - (textWidth / 2),
            y: page.getHeight() - yCurrentLine,
            size: textLine.fontSize,
            color: textLine.color
          });
        }

        // Generate the PDF as a Uint8Array
        const pdfBytes = await pdfDoc.save();

        // Create a blob from the PDF data and create a URL
        const blob = new Blob([pdfBytes], { type: 'application/pdf' });
        const url = URL.createObjectURL(blob);

        // Open the PDF in a new tab
        window.open(url);
      };
    </script>
  </body>
</html>

pdf-lib.js-center text.png
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,058
Latest member
QQXCharlot

Latest Threads

Top