Erro encode UTF-8 microsoft graph (I got ÇÃODE) - React Js -PWA

Diego Leonardo Dimitroff Petcoff 0 Reputation points
2024-01-29T12:41:39.4566667+00:00

Hello community,

I am encountering a character encoding issue while attempting to generate a PDF using jsPDF from a React application and sending it through Microsoft Graph. The following is the code I want to convert to a PDF (note that the content to be converted is inside "id=projectPDF").

My HTML is in Portuguese:

<!DOCTYPE html>
<html lang="pt">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" type="image/svg+xml" href="/INDIRE_LOGO.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="theme-color" content="#000000" />
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
      crossorigin="anonymous"
    />

    <meta name="Indire" content="PWA created to be Used by Indire Company" />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/INDIRE_LOGO.png"" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>Indire</title>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
      crossorigin="anonymous"
    ></script>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

And the JavaScript code triggering the PDF conversion:

<div id="projectPDF" style={{ width: "100%" }}>
{errorMessage && <h1>{errorMessage}</h1>}
<form onSubmit={handleSubmite}>
<Summary setTitle={setTitle}  title={title} setSub_title={setSub_title}  sub_title={sub_title}          setAddress={setAddress}   adrress={address}/>
<IntroductionInput  introduction={introduction} setIntroduction={setIntroduction}/>        <Gral_description gral_description={gral_description} setGral_description={setGral_description}/>        <button style={{background: "blue"}}>CREAR PDF CON FORM CONTENT </button>
</form>
<input style={{background: "pink"}} type="file" onChange={handleFileChange}/>
</div>

I have a function that gets activated when a button is pressed:

 PDFMakerHTML(document.getElementById("projectPDF"));

In this case, the function I am sending the HTML to is:

export const PDFMakerHTML = async (html) => {

  var doc = new jsPDF("p", "px", [1000, 1400]);
  doc.setLanguage("pt");
  doc.internal.charset = "utf-8";

  await doc.html(html, {
    callback: async function (doc) {
      doc.save("documentPDF-HTML");
      let pdf = doc.output("datauristring");

      window.open(pdf, "_blank");
      var url = pdf.split(",");
      var base64Data = url[1];
      var decodedData = window.atob(base64Data);

      //CONVERT TO A BLOB OBJECT
      FetchPostMicrosoftGraph(
        new Blob([decodedData], { type: "application/pdf;charset=utf-8" })
      );

      
    },
    x: 250,
    y: 0,
  });
 
};

I've also created a function called FetchPostMicrosoftGraph() to which I send the code in a Blob:


import { Auth } from "../utils/auth";

export const FetchPostMicrosoftGraph = async (file) => {
  try {
const accessToken = await Auth();
var root = "https://graph.microsoft.com/v1.0/me/drive/root:";
var path = "/Pruebas-Test/PRUEBA2-18-2024.pdf:/content";
var url = root + encodeURIComponent(path);

const response = await fetch(url, {
  method: "PUT",
  headers: {
    Authorization: `Bearer ${accessToken}`,
    "Content-Type": "application/pdf;charset=utf-8",
    "Accept-Language": "pt",
  },

  body: file,
});

if (response.ok) {
  console.log("El archivo se ha subido exitosamente.");
  return "File uploaded successfully";
} else {
  console.error(
    `Error al subir el archivo. Código de estado: ${response.status}`
  );
  throw new Error(`Error uploading file. Status code: ${response.status}`);
}
} catch (error) {

console.error("Error en FetchPostMicrosoftGraph:", error);
throw new Error(
  "Hubo un problema al subir el archivo al servidor. Por favor, inténtelo de nuevo más tarde."
);
}
};

As seen in the code, I need the text to be interpreted with special characters in Portuguese, which is why I added "Accept-Language": "pt" (I have also tried using pt_BR for Brazil, but it doesn't work).

The PDF file is downloaded and previewed correctly in a popup window. For example, the text "INTERVENÇÃODE REABILITAÇÃO" is displayed correctly. However, when the document is saved in OneDrive in the specified folder (var path = "/Pruebas-Test/PRUEBA2-18-2024.pdf:/content"), the same phrase is not displayed correctly. Instead, it appears as "INTERVENÇÃODE REABILITAÇÃO". Additionally, the image is not visible.

Any guidance on resolving these issues would be greatly appreciated.

Thank you!

Microsoft 365 and Office | Development | Office JavaScript API
Microsoft Security | Microsoft Graph
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.