Home > Software design >  how to make or correct PDF data in response Nodejs
how to make or correct PDF data in response Nodejs

Time:11-20

Getting response %PDF-1.4\n%����\n6 0 obj\n<</Type/XObject/Subtype/Image/Width 29/Height 29/Length 125/ColorSpace/DeviceGray/BitsPerComponent 1/Filter/CCITTFaxDecode/DecodeParms<</K -1/BlackIs1 true/Columns 29/Rows 29>>>>stream\n&����)�9_��~G?�A�G����?�q��(r�\b(�q�GA9�<?T\r���TD<D\�c��A�,Db������ ���\b����t\bdw�$�I/�\b.�"��G�

How to fix this response as readable pdf form please guide

const PDFDocument = require("pdfkit");

 router.post("/get/PDF", (req, res) => {
  axios({
    method: "POST",
    url: "http://143.155.55.11:8080/getPDF",
    data: {
      id: 1,
      size: "A4",
    },
    headers: {
      "Content-Type": "application/json",
    },
  })
    .then(function (result) {
      const doc = new PDFDocument();
      let filename = "download";
      // Stripping special characters
      filename = encodeURIComponent(filename)   ".pdf";
      // Setting response to 'attachment' (download).
      // If you use 'inline' here it will automatically open the PDF
      res.setHeader(
        "Content-disposition",
        'attachment; filename="'   filename   '"'
      );
      res.setHeader("Content-type", "application/pdf");
      const content = encodeURIComponent(result.data);
      doc.y = 300;
      doc.text(content, 50, 50);
      doc.pipe(res);
      doc.end();
    })
    .catch(function (error) {
      return res.status(500).json({
        data: error,
        status: "error",
        message: "Something went wrong.",
      });
    });
});

CodePudding user response:

 router.post("/get/PDF", (req, res) => {
  axios({
    method: "POST",
    url: "http://143.155.55.11:8080/getPDF",
    data: {
      id: 1,
      size: "A4",
    },
    headers: {
      "Content-Type": "application/json",
    },
  })
    .then(function (result) {
      const base64Str = Buffer.from(result.data).toString("base64");
  
        let decodedBase64 = await base64topdf.base64Decode(
          base64Str,
          "download.pdf"
        );
        const fileContent = fs.readFileSync("download.pdf");

        return res.status(200).json({
          status: "success",
          message: "Data send successfully.",
        });
    })
    .catch(function (error) {
      return res.status(500).json({
        data: error,
        status: "error",
        message: "Something went wrong.",
      });
    });
});
  • Related