Thank you guys this solution is helping me but im having the error 413.
Let me explain better, i created an website that the owner wants to allow the clients to get access of the reports of their provided service and in the end it must allow to download this report selected when cliecked on a button, i managed to do all of it except the pdf download of the file and with your help i managed that but since there are many images on my database on wix i can only get a few images and when i try to get more images on the pdf it gives me the error 413 how can i solve this situation. Just to mention im a beginner.
this is my code:
export async function btnDownloadPdf_click(event) {
$w('#btnBaixarPdf').collapse();
$w('#imgLoading').expand();
const datas = $w('#rptListDownload').data;
// Set filename
const fileName = `Report_${datas[0].monthReport}`;
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create();
// Embed the Times Roman font
const timesRomanFont = await pdfDoc.embedFont(StandardFonts.Helvetica);
// Add a blank page to the document
const page = pdfDoc.addPage([595.276, 841.890]);
// Get the width and height of the page
const { width, height } = page.getSize();
const cmToPoints = (cm) => cm * 16.35; // Convert cm to points
const imageBytes1 = await fetch('https://res.cloudinary.com/drhmgeae5/image/upload/v1692208742/logotipos_am8vme.png').then((response) => response.arrayBuffer());
const imageLogo1 = await pdfDoc.embedPng(imageBytes1);
const imageBytes2 = await fetch('https://res.cloudinary.com/drhmgeae5/image/upload/v1692208742/logotipovemprobus_1_acrtte.png').then((response) => response.arrayBuffer());
const imageLogo2 = await pdfDoc.embedPng(imageBytes2);
const imageWidth = 60; // Adjust the image width as needed
const xPosition = (page.getWidth() - 2 * imageWidth) / 2;
// Calculate the y-coordinate for both images to position them 5 cm from the top
const yPosition = page.getHeight() - cmToPoints(5);
// Draw the first image
page.drawImage(imageLogo1, {
x: xPosition,
y: yPosition,
width: imageWidth,
height: 60,
});
// Draw the second image next to the first image
page.drawImage(imageLogo2, {
x: xPosition + imageWidth,
y: yPosition,
width: imageWidth,
height: 40,
});
const counter = datas.length; // Count the number of arrays
// Query the Wix database collection to retrieve the user's information
const userId = datas[0].user; // Replace with the actual user identifier
const userResult = await wixData.query('Users')
.eq('_id', userId) // Assuming '_id' is the unique identifier field
.find();
if (userResult.items.length > 0) {
// Get the user's name from the retrieved data
const userName = userResult.items[0].company; // Replace 'nome' with the actual property name for the user's name
// Example: Add text with the user's name
page.drawText(`Client : ${userName}`, {
x: 30,
y: 725,
size: 11,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
} else {
console.error('User not found in the database');
}
// Query the Wix database collection to retrieve the user's information
const TipoId = datas[0].user; // Replace with the actual user identifier
const results = await wixData.query('Contrato')
.eq('Users', TypeId) // Assuming '_id' is the unique identifier field
.find();
if (results.items.length > 0) {
// Get the user's name from the retrieved data
const typePublicity = results.items[0].typePublicity; // Replace 'nome' with the actual property name for the user's name
// Example: Add text with the user's name
page.drawText(`Publicity type : ${typePublicity}`, {
x: 250,
y: 725,
size: 11,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
} else {
console.error('User not found in the database');
}
// Example: Add text
page.drawText(`Month : ${datas[0].monthReport}`, {
x: 30,
y: 705,
size: 11,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Example: Add text
page.drawText(`Year : ${datas[0].yearReport}`, {
x: 150,
y: 705,
size: 11,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Example: Add text
page.drawText(`# of cars : ${counter}`, {
x: 220,
y: 705,
size: 11,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Example: Add text
page.drawText(`Time of report : ${formatDate(datas[0].monthOfReport)} - ${formatDate(datas[0].dateOfWork)}`, {
x: 320,
y: 705,
size: 11,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Initialize the starting y-coordinate
let y = 675;
const contentHeight = 20; // Adjust this value based on your content
// Define a function to add a new page to the PDF
const addNewPage = () => {
const pageHeight = 841.890; // Adjust to your page height
const remainingSpace = y - contentHeight; // Calculate the remaining space on the current page
if (remainingSpace < 30) {
currentPage = pdfDoc.addPage([595.276, pageHeight]);
y = pageHeight - 30; // Reset y-coordinate for the new page
}
// Add any page-specific content or headers here
return currentPage;
};
// Iterate through the repeater data and add it to the PDF
let currentPage = addNewPage(); // Initial page
let xy = 20; // Initial y-coordinate
// Iterate through the repeater data and add it to the PDF
for (let index = 0; index < datas.length; index++) {
const item = datas[index];
// Fetch and embed images for the current item
const fullAttachmentReport = getFullImageURL(item.attachTheReport);
const fullAttachmentOfBack= getFullImageURL(item.attachTheBack);
const fullAttachmentOfLeft = getFullImageURL(item.attachTheLeft);
const fullAttachmentOfRight = getFullImageURL(item.attachTheRight);
const imageCalendar = await fetch(fullAttachmentReport).then((response) => response.arrayBuffer());
const image1 = await pdfDoc.embedJpg(imageCalendar);
const imageBack = await fetch(fullAttachmentOfBack).then((response) => response.arrayBuffer());
const image2 = await pdfDoc.embedJpg(imageBack);
const imageLeft = await fetch(fullAttachmentOfLeft).then((response) => response.arrayBuffer());
const image3 = await pdfDoc.embedJpg(imageLeft);
const imageRight = await fetch(fullAttachmentOfRight).then((response) => response.arrayBuffer());
const image4 = await pdfDoc.embedJpg(imageRight);
// Count the number of indexed arrays
const count = index + 1;
// Add text
page.drawText(`${count}`, {
x: 30,
y,
size: 10,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Add text
page.drawText(`Plate : ${item.plate}`, {
x: 50,
y,
size: 10,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Add text
page.drawText(`days driven : ${item.daysDriven}`, {
x: 190,
y,
size: 10,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Add text
page.drawText(`Days Stoped : ${item.daysStoped}`, {
x: 300,
y,
size: 10,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Add text
page.drawText(`City : ${item.city}`, {
x: 420,
y,
size: 10,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Increment the y-coordinate for the next set of data
y -= 15; // Move down by 20 units for the next item
// Add text
page.drawText(`Description : ${item.description}`, {
x: 50,
y,
size: 10,
font: timesRomanFont,
color: rgb(0, 0.53, 0.71),
});
// Increment the y-coordinate for the next set of data
y -= 85; // Move down by 85 units for the next item
// Calculate the total width of the two images and the space between them
const totalWidth = 2 * 180; // Assuming each image has a width of 80 units
const spaceBetweenImages = 150; // Adjust this value as needed
// Calculate the starting x-coordinate for the first image
const startX = (page.getWidth() - totalWidth - spaceBetweenImages) / 2;
// Calculate the total width of the two images and the space between them
const totalWidth2 = 2 * 180; // Assuming each image has a width of 80 units
const spaceBetweenImages2 = 150; // Adjust this value as needed
// Calculate the starting x-coordinate for the first image
const startX2 = (page.getWidth() - totalWidth2 - spaceBetweenImages2) / 2;
// Add the first embedded image (image1) to the PDF page
page.drawImage(image1, {
x: startX,
y, // You should set the 'y' coordinate to position the image
width: 135, // Set the width of the first image
height: 75, // Set the height of the first image
});
// Add the second embedded image (image2) to the PDF page, positioned next to the first image
page.drawImage(image2, {
x: startX + 50 + spaceBetweenImages, // Position it to the right of the first image
y, // Set the 'y' coordinate to match the position of the first image
width: 135, // Set the width of the second image
height: 75, // Set the height of the second image
});
// Add the first embedded image (image1) to the PDF page
page.drawImage(image3, {
x: startX + 230 + spaceBetweenImages,
y, // You should set the 'y' coordinate to position the image
width: 135, // Set the width of the first image
height: 75, // Set the height of the first image
});
// Increment the y-coordinate for the next set of data
y -= 85; // Move down by 20 units for the next item
// Add the second embedded image (image2) to the PDF page, positioned next to the first image
page.drawImage(image4, {
x: startX2, // Position it to the right of the first image
y, // Set the 'y' coordinate to match the position of the first image
width: 135, // Set the width of the second image
height: 75, // Set the height of the second image
});
// Increment the y-coordinate for the next set of data
y -= 30; // Move down by 20 units for the next item
// Increment the y-coordinate for the next set of data
xy -= contentHeight; // Move down by contentHeight units for the next item
}
// Serialize the PDFDocument to Base64
const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
const dataUriPrefix = 'data:application/pdf;base64,';
const base64 = pdfDataUri.slice(dataUriPrefix.length);
console.log("pdfDataUri:", pdfDataUri);
console.log("base64:", base64);
savePDF(base64, fileName)
.then(downloadUrl => {
console.log("download Url", downloadUrl);
wixLocation.to(downloadUrl); //only works when published
$w('#imgLoading').collapse();
$w('#btnDownloadPdf').expand();
})
.catch((error) => {
console.error("1 Erro ocorreu ao gravar o PDF: ", error);
$w('#imgLoading').collapse();
$w('#btnDownloadPdf').expand();
});
}