Skip to content

Commit

Permalink
Merge pull request smaranjitghose#1005 from N-Shar-ma/fix-image-pdf-size
Browse files Browse the repository at this point in the history
Fixed Image to PDF conversion, Resolution and Dimensions preserved
  • Loading branch information
anushbhatia authored May 31, 2021
2 parents 42aa167 + f01e078 commit 341b251
Showing 1 changed file with 19 additions and 23 deletions.
42 changes: 19 additions & 23 deletions src/pages/MediaManip/MediaManip.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,13 @@ export default function MediaManip() {
canvas.height = img.height;
canvas.getContext("2d").drawImage(img, 0, 0);
const dataUrl = canvas.toDataURL(
`image/${format !== "pdf" ? format : "png"}`
`image/${format!=="pdf" ? format : "png"}`
);
if (format === "pdf") {
dataUrls.push(dataUrl);
if (dataUrls.length === files.length) {
const width = img.width;
const height = img.height;
if(format === "pdf") {
dataUrls.push({ dataUrl, width, height });
if(dataUrls.length === files.length) {
downloadPdf(dataUrls);
return;
}
Expand All @@ -108,30 +110,24 @@ export default function MediaManip() {
});
});
};

const downloadPdf = async (images) => {
const doc = new jsPDF("p", "pt", "a4");
const width = doc.internal.pageSize.width;
const height = doc.internal.pageSize.height;

const downloadPdf = (images) => {
const doc = new jsPDF("l", "px", [images[0].width, images[0].height]);
doc.deletePage(1);
doc.text(10, 20, "");
images.forEach((imgDataUri, i) => {
if (i > 0) {
doc.addPage();
doc.setPage(i + 1);
images.forEach(({ dataUrl, width, height }, i) => {
doc.addPage([width, height]);
doc.setPage(i + 1);
doc.addImage(dataUrl, "PNG", 0, 0, width, height);
if(i === images.length - 1) {
doc.save("converted.pdf"); //save PDF
setConvertedFiles([]);
}
doc.addImage(imgDataUri, "PNG", 0, 0, width, height);
});

await new Promise((resolve) => {
// Wait for PDF download
doc.save("document.pdf"); //save PDF
resolve(true);
setConvertedFiles([]);
});
};

const onDownload = () => {
if (convertedFiles.length === 0) return;
if(convertedFiles.length === 0) return;
convertedFiles.forEach((item, index) => {
zip.file(`${index}.${item.type}`, item.data, { base64: true });
});
Expand Down

0 comments on commit 341b251

Please sign in to comment.