I have this code. The goal is to print a PDF once a button is clicked. It works on all platforms except iOS.On iOS, the print dialog does not appear automatically. The reason iOS should display with different code is that it prints the website, not the PDF. This code fixes that, except the print dialog does not automatically appear.
Here is the code:
const printMenu = async () => {
const { data } = await useFetch(
"https://*****/", {
method: "GET",
query: {
websiteId: "0r5bGoJkXJ0k4vMjb900",
contentGroupId: "lwTMIfak4naAVflMtMpk",
contentItemId: props.contentItemId,
},
});
const pdf_url = (data.value as any).data.image_urls[0];
try {
const loadingTask = window.pdfjsLib.getDocument(pdf_url);
const pdf = await loadingTask.promise;
const scale = 1.5;
// Get number of pages in PDF
const numPages = pdf.numPages;
// Create a new div which will hold all canvases (one for each page)
const allPagesDiv = document.createElement('div');
// Loop over all pages
for (let i = 1; i <= numPages; i++) {
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: scale });
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
if (!context) {
throw new Error('Unable to get 2d context from canvas');
}
canvas.height = viewport.height;
canvas.width = viewport.width;
const renderContext = {
canvasContext: context,
viewport: viewport
};
await page.render(renderContext).promise;
// Append this canvas to the allPagesDiv
allPagesDiv.appendChild(canvas);
}
// Check if it's Safari on iOS
const isIOS = /iPad|iPhone|iPod/.test(navigator.platform || "");
if (isIOS) {
// Open the PDF in a new window and instruct the user to manually print it
const newWindow = window.open(pdf_url, '_blank');
setTimeout(() => {
if (newWindow) {
newWindow.print();
}
}, 250);
} else {
const current = window.document.body.innerHTML;
const printWindow = window;
printWindow.document.body.innerHTML = '';
printWindow.document.body.appendChild(allPagesDiv);
printWindow.print();
printWindow.document.body.innerHTML = current;
}
} catch (error) {
console.error("Error printing PDF: ", error);
}
};