<repo_name>HicirTech/JustWantPDF<file_sep>/README.md
# Just Want PDF

<a href="https://www.npmjs.com/package/just-want-pdf">
    <img
      src="https://img.shields.io/npm/v/just-want-pdf.svg?style=flat-square"
      alt="NPM Version"
    />
</a>

Just-Want-PDF is a package to help you to get PDF in node.js envrionment.  
Takes in many files, marge them, and output a single PDF result
<hr/>


<a href="https://hicirtech.github.io/JustWantPDF/">
    Demo Here
</a>

### Accept input file types

`.PDF` `.jpg` `.jpge` `.png`

### Output

`Byte Array` or `Blob Object` or `File Object`

### Usage

install package
`npm i just-want-pdf`

import to your project
`import converter from "just-want-pdf";`

Convertion

**Assumption**

```
import converter from "just-want-pdf";
var fileList = [File1, File2, File3...];
```

to byte array
` const result = converter.toByte(fileList)`

to blob
` const result = converter.toBlob(fileList)`

to File
` const result = converter.toFile(fileList)`

for display in iframe

```
    .....

    var result = convert.toBlob(fileList);
    const url =URL.createObjectURL(result);

    //use iframe to display url

    <iFrame src = {url} />

    ....
```
<file_sep>/index.js
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";

const toBuffer = async (file) => {
  var buffer = await file.arrayBuffer();
  return buffer;
};

const toByte = async (files) => {
  const pdfDoc = await PDFDocument.create();
  for (var i = 0; i != files.length; i++) {
    var buffer = await toBuffer(files[i]);
    var type = files[i].type;

    if (type == "application/pdf") {
      const loader = await PDFDocument.load(buffer);
      var j = 0;
      while (true) {
        try {
          const [firstDonorPage] = await pdfDoc.copyPages(loader, [j]);
          pdfDoc.addPage(firstDonorPage);
          j++;
        } catch (e) {
          break;
        }
      }
    } else {
      const page = pdfDoc.addPage();
      const { width, height } = page.getSize();
      var image;
      if (type == "image/jpeg") {
        image = await pdfDoc.embedJpg(buffer);
        page.setSize(image.width, image.height);
        page.drawImage(image);
      } else if (type == "image/png") {
        image = await pdfDoc.embedPng(buffer);
        page.setSize(image.width, image.height);
        page.drawImage(image);
      }
    }
  }
  const pdfBytes = await pdfDoc.save();
  return pdfBytes;
};

const toBlob = async (files) => {
  var b = await toByte(files);
  var blob = new Blob([b], { type: "application/pdf" });

  return blob;
};

const toFile = async (files) => {
  var blob = toBlob(files);
  var f = new File([blob], "result.pdf");
  return f;
};

const converter = {
  toFile: toFile,
  toByte: toByte,
  toBlob: toBlob,
};
export default converter;
