Ms document convert to pdf

WebViewer Version: 10.4.0

Do you have an issue with a specific file(s)?yes
Can you reproduce using one of our samples or online demos?no
Are you using the WebViewer server?yes
Does the issue only happen on certain browsers?no its not base on browser
Is your issue related to a front-end framework?maybe
Is your issue related to annotations?no

Please give a brief summary of your issue:
i am getting an issue on ms office document for annotation so i have create function to convert ms document to pdf but its not working so please help me to convert non pdf blob file to pdf and display in my web viewer
(Think of this as an email subject)

Please describe your issue and provide steps to reproduce it:
(The more descriptive your answer, the faster we are able to help you)

Please provide a link to a minimal sample where the issue is reproducible:
const getMimeTypeFromFileName = (fileName) => {
const mimeTypes = {
pdf: “application/pdf”,
jpg: “image/jpeg”,
jpeg: “image/jpeg”,
png: “image/png”,
txt: “text/plain”,
csv: “text/csv”,
doc: “application/msword”,
dot: “application/msword”,
docx: “application/vnd.openxmlformats-officedocument.wordprocessingml.document”,
dotx: “application/vnd.openxmlformats-officedocument.wordprocessingml.template”,
docm: “application/vnd.ms-word.document.macroEnabled.12”,
dotm: “application/vnd.ms-word.template.macroEnabled.12”,
xls: “application/vnd.ms-excel”,
xlt: “application/vnd.ms-excel”,
xla: “application/vnd.ms-excel”,
xlsx: “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”,
xltx: “application/vnd.openxmlformats-officedocument.spreadsheetml.template”,
xlsm: “application/vnd.ms-excel.sheet.macroEnabled.12”,
xltm: “application/vnd.ms-excel.template.macroEnabled.12”,
xlam: “application/vnd.ms-excel.addin.macroEnabled.12”,
xlsb: “application/vnd.ms-excel.sheet.binary.macroEnabled.12”,
ppt: “application/vnd.ms-powerpoint”,
pot: “application/vnd.ms-powerpoint”,
pps: “application/vnd.ms-powerpoint”,
ppa: “application/vnd.ms-powerpoint”,
pptx: “application/vnd.openxmlformats-officedocument.presentationml.presentation”,
potx: “application/vnd.openxmlformats-officedocument.presentationml.template”,
ppsx: “application/vnd.openxmlformats-officedocument.presentationml.slideshow”,
ppam: “application/vnd.ms-powerpoint.addin.macroEnabled.12”,
pptm: “application/vnd.ms-powerpoint.presentation.macroEnabled.12”,
potm: “application/vnd.ms-powerpoint.template.macroEnabled.12”,
ppsm: “application/vnd.ms-powerpoint.slideshow.macroEnabled.12”,
mdb: “application/vnd.ms-access”,
// add more file types here
};

const fileExtension = fileName.split(".").pop().toLowerCase();
return mimeTypes[fileExtension] || "application/octet-stream"; // default to binary stream if not found

};
const getFileExtension = (fileName) => {
const parts = fileName.split(“.”);
return parts.length > 1 ? parts.pop() : “”; // Return the extension or an empty string if no extension
};
// Initialize WebViewer
useEffect(() => {
if (pdfResponseData.attachmentBlob) {
WebViewer(
{
path: “/webviewer/lib”,
licenseKey:
“1693909073058:7c3553ec030000000025c35b7559d8f130f298d30d4b45c2bfd67217fd”, // Replace with your key
fullAPI: true,
officeEditor: true, // Enables Office file support
officeWorker: true, // Enables Office file conversion
},
viewer.current
).then((instance) => {
console.log(“pdfResponseDatapdf”, instance.Core); // Debugging step

    const { documentViewer, annotationManager, officeToPDFBuffer, PDFNet } =
      instance.Core;
    console.log(
      "pdfResponseDatapdf officeToPDFBuffer available:",
      officeToPDFBuffer
    );

    // Example usage:
    const extension = getFileExtension(fileName);
    const mimeType = getMimeTypeFromFileName(fileName);
    let blob = base64ToBlob(pdfResponseData.attachmentBlob, mimeType); // Convert Base64 to Blob
    if (extension.toLowerCase() === "pdf") {
      instance.UI.loadDocument(blob, {
        filename: fileName,
      });
    } else {
      if (["docx", "xlsx", "pptx"].includes(extension.toLowerCase())) {
        try {
          (async () => {
            // Initialize Document Conversion
            console.log("pdfResponseDatapdf Starting conversion...");
            // Convert Blob into a File object
            const file = new File([blob], `${fileName}`, {
              type: mimeType,
            });
            const buffer = await officeToPDFBuffer(file, {
              l: "1693909073058:7c3553ec030000000025c35b7559d8f130f298d30d4b45c2bfd67217fd", // Replace with your key
            });
            // Create a Blob for the converted PDF
            const convertedBlob = new Blob([buffer], {
              type: "application/pdf",
            });
            // **Remove existing extension from fileName before appending '.pdf'**
            const sanitizedFileName = fileName.replace(/\.[^/.]+$/, ""); // Removes the last extension
            // Load the converted PDF into WebViewer
            instance.UI.loadDocument(convertedBlob, {
              filename: `${sanitizedFileName}.pdf`, // Use sanitized filename
            });
          })();
        } catch (error) {
          console.log("Conversion failed:", error); // Logs full error object
          console.log("Error Details:", JSON.stringify(error, null, 2)); // Detailed JSON
        }
      }
    }

    // Handle annotations
    documentViewer.addEventListener("documentLoaded", () => {
      annotationManager.setCurrentUser(localStorage.getItem("name"));
      if (pdfResponseData.xfdfData) {
        annotationManager.importAnnotations(pdfResponseData.xfdfData);
      }
    });

    // Set permissions if needed
    if (Number(isPermission) === 1) setPermissions(instance);

    // Add custom save button
    instance.UI.setHeaderItems((header) => {
      header.push({
        type: "actionButton",
        img: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>',
        onClick: async () => saveAnnotations(annotationManager),
      });
    });
  });
}

}, [pdfResponseData.attachmentBlob]);

1 Like

i have solve this issue issue what i under stand is web viewer is not properly work on ms office files so we have to convert it before load document into pdf so i have done it and load it then make some annotations on different page after saving my annotation when i reload my document its perfectly shown annotation on their places this is the solution …

// Initialize WebViewer
useEffect(() => {
if (pdfResponseData.attachmentBlob) {
WebViewer(
{
path: “/webviewer/lib”,
licenseKey:
“xyz”, // Replace with your key
fullAPI: true,
officeEditor: true, // Enables Office file support
officeWorker: true, // Enables Office file conversion
},
viewer.current
).then((instance) => {

    const { documentViewer, annotationManager, officeToPDFBuffer, PDFNet } =
      instance.Core;
    // Example usage:
    const extension = getFileExtension(fileName);
    const mimeType = getMimeTypeFromFileName(fileName);
    let blob = base64ToBlob(pdfResponseData.attachmentBlob, mimeType); // Convert Base64 to Blob
    const supportedFormats = [
      "pdf",
      "webp",
      "svg",
      "png",
      "jpeg",
      "gif",
      "avif",
      "apng",
    ];

    // Check if the extension exists in the array (case-insensitive)
    if (supportedFormats.includes(extension.toLowerCase())) {
      instance.UI.loadDocument(blob, {
        filename: fileName,
      });
    } else {
      if (["docx", "xlsx", "pptx"].includes(extension.toLowerCase())) {
        try {
          (async () => {
            // Initialize Document Conversion
            // Convert Blob into a File object
            const file = new File([blob], `${fileName}`, {
              type: mimeType,
            });
            const buffer = await officeToPDFBuffer(file);
            // Create a Blob for the converted PDF
            const convertedBlob = new Blob([buffer], {
              type: "application/pdf",
            });
            // **Remove existing extension from fileName before appending '.pdf'**
            const sanitizedFileName = fileName.replace(/\.[^/.]+$/, ""); // Removes the last extension
            // Load the converted PDF into WebViewer
            await instance.UI.loadDocument(convertedBlob, {
              filename: `${sanitizedFileName}.pdf`,
              extension: "pdf",
            });
          })();
        } catch (error) {
          console.log("pdfResponseDatapdf Conversion failed:", error); // Logs full error object
        }
      }
    }

    // Handle annotations
    documentViewer.addEventListener("documentLoaded", () => {
      annotationManager.setCurrentUser(localStorage.getItem("name"));
      if (pdfResponseData.xfdfData) {
        annotationManager.importAnnotations(pdfResponseData.xfdfData);
      }
    });

    // Set permissions if needed
    if (Number(isPermission) === 1) setPermissions(instance);

    // Add custom save button
    instance.UI.setHeaderItems((header) => {
      header.push({
        type: "actionButton",
        img: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M0 0h24v24H0z" fill="none"/><path d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/></svg>',
        onClick: async () => saveAnnotations(annotationManager),
      });
    });
  });
}

}, [pdfResponseData.attachmentBlob]);

1 Like