How do I convert a PDF to multiple PNG images using node.js and MongoDB in the backend?

86 Views Asked by At

**pdf to image conversion using node js and MongoDB **

I am doing to convert the PDF file into multiple png images using pdf-to-image convert npm package. I assign the converted image to 'images' variable it give me a array of buffer images then I want to push the array of images to the uploadModel image variable but I failed to do it. how can I do it?

mage Model schema I

const mongoose = require('mongoose');

const imagesSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    data: {
        type:  Buffer,
        required: true
    }
});

const ImagesModel = mongoose.model('PdfImages', imagesSchema )
module.exports = ImagesModel

Upload Model Schema

const mongoose = require('mongoose');

const uploadSchema = new mongoose.Schema({
  filename: String,
  data: {
    type: Buffer,
    required: true
  },
  contentType: {
    type: Buffer,
    required: true
  },
  fullName: String,
  email: String,
  images: {
    type:  Array,
    required: true
  },
});

const uploadModel = mongoose.model('Pdf', uploadSchema);

module.exports = uploadModel;
const express = require("express");
const mongoose = require("mongoose");
const multer = require("multer");
const pdfImgConvert = require("pdf-img-convert");
const uploadModel = require("./models/uploadModel");
const ImagesModel = require("./models/ImagesModel");
const cors = require("cors");
const bodyParser = require("body-parser");
require("dotenv/config");

const app = express();
app.use(cors()) / app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Connect to mongodb Atlas
mongoose
  .connect(
    ``,
    {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }
  )
  .then(() => {
    console.log("Connected to mongodb successfully");
  })
  .catch((error) => {
    console.log("No connection, " + error);
  });

// Store file in buffer or server'memory instead of disk
const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 10000000 }, // 10mb
});

const ImageSchema = new mongoose.Schema({
  data: { type: Buffer, required: true },
});
const ImageModel = mongoose.model("Image", ImageSchema);

app.post('/uploadForm', upload.single('myFile'), async (req, res) => {

  try {
    const fileBuffer = req.file.buffer;
    const fileType  = req.file.mimetype;
    if (fileType !== 'application/pdf'){
      return  res.send({
        success:  "wrongFile" ,
        message : "Please upload pdf file only"})
    }

    // Convert the PDF file to images using pdfImgConvert
    const images = await pdfImgConvert.convert(fileBuffer, {
      width: 300, //Number in px
      height: 300, // Number in px
      density: 300,
      format: 'png',
    });

    const uploadDoc = new uploadModel({
      filename: req.file.originalname,
      data: fileBuffer,
      contentType: fileType,
      fullName: req.body.fullName,
      email: req.body.email,
      images: []
    });
    //  As images return ArrayBuffer so convert it to Buffer
    const imageObjects = images.map(image => ({ data: Buffer.from(image) }));
    const base64Images = images.map((image) => image.toString("base64"));
    console.log("this is base 64 ",base64Images);

    // Insert All images of pdf at once in db
    const savedImages = await ImagesModel.insertMany(imageObjects);
    // Add the IDs of the images to the document's images array
    uploadDoc.images = savedImages.map((image) => {
      return image._id;
    });

    const savedUpload = await uploadDoc.save();

    res.send({
      success: true,
      message: "Submitted Sucessfully",
      upload: savedUpload,
    });

  } catch (error) {
    console.error('Error processing file upload:', error);
    res.status(500).send({
      success:  false,
      message: 'An error occured, Please try again.'
    });
  }
});

app.get('/pdf/:id', async (req, res) => {
  try {
    const uploadId = req.params.id;
    const upload = await uploadModel.findById(uploadId);

    if (!upload) {
      return res.status(404).json({ success: false, message: 'PDF not found' });
    }

    const images = await ImagesModel.find({ _id: { $in: upload.images } });

    const formattedImages = images.map((image) => ({
      _id: image._id,
      data: image.data.toString('base64')
    }));

     console.log(formattedImages);
    res.json({ success: true, upload, images: formattedImages });

  } catch (error) {
    console.error('Error retrieving PDF and images:', error);
    res.status(500).json({
      success: false,
      message: 'An error occurred while retrieving the PDF and images' });
  }
});


app.listen(3000, () => {
  console.log("server running at: 3000");
});

i tried to convert a pdf to multiple png images

0

There are 0 best solutions below