Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
7.02k stars 676 forks source link

Update README.md #1560

Open shivamMukhia opened 12 months ago

shivamMukhia commented 12 months ago

What?

I added a new function to facilitate the download of generated PDFs in a Node.js environment. This function uses the fs module to write the PDF bytes to a file, allowing users to easily save the generated PDF on their local machine. Example code snippet:

const { PDFDocument, StandardFonts, rgb } = require('pdf-lib');
const fs = require('fs').promises; // Using promises version for async/await

// Create a new PDFDocument
async function createPDF () {
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()

  // Save PDF bytes to a file
  await fs.writeFile('output.pdf', pdfBytes);

  console.log('PDF saved as "output.pdf"');

// For example, `pdfBytes` can be:
//   • Written to a file in Node
//   • Downloaded from the browser
//   • Rendered in an <iframe>
}
createPDF();

Why?

This PR aims to enhance the user experience by providing a convenient way to download generated PDFs in a Node.js environment. Users can now easily integrate the download functionality into their applications without having to manually handle the file-writing process.

How?

I added a new function createPDFAndDownload that encapsulates the PDF generation and download process. It uses the fs module to write the generated PDF bytes to a file named "output.pdf". Users can call this function to both generate and download a PDF in a single step.

Alternative implementations were considered, but using the fs module for simplicity and compatibility with Node.js was chosen as the most straightforward approach.

Testing?

I tested the new function by running it in a Node.js environment. I verified that the generated PDF is correctly saved as "output.pdf"

New Dependencies?

No.

Screenshots

N/A.

Suggested Reading?

No.

Anything Else?

The new function should be straightforward to use, and users can customize the filename and path as needed.

Checklist