exif orientation is handled incorrectly
Fuzzyma opened this issue · 7 comments
jspdf handles exif orientation and correctly flips width and height. However, it does not actually rotate the image. Instead it just stretches the unrotated image into its rotated shape.
This issue has been rised twice already but it seems that nobody realized that the image is not correctly rotated
In both issues you can actually see, that albeit the image dimension was rotated, the content was not.
I encountered the issue when using svg2pdf.js. You can also see another example in the issue I raised: yWorks/svg2pdf.js#315. The orientation is correct, the content is still unrotated and just stretched
I am facing same issue with addImage function, it does not respect exif orientation.
Bellow you can find my suboptimal solution if anyone needs it before this gets addressed.
Uses canvas to draw image first, canvas rendering will display image correctly then grabbing data and passing it to addImage fn.
import jsPDF from 'jspdf';
async function createImage(src: string) {
const img = new Image();
img.src = src;
img.setAttribute('crossorigin', 'anonymous');
return new Promise<{
width: number;
height: number;
imageCanvasData: string;
}>((resolve) => {
img.onload = () => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
ctx?.drawImage(img, 0, 0, img.width, img.height);
const imageCanvasData = canvas.toDataURL('image/jpeg');
canvas.remove();
resolve({ width: img.width, height: img.height, imageCanvasData });
};
img.onerror = () => resolve({ width: 0, height: 0, imageCanvasData: '' });
});
}
const pdf = new jsPDF();
const { width, height, imageCanvasData } = await createImage(
'https://images.unsplash.com/photo-1504805572947-34fad45aed93?q=20&w=200',
);
console.log(width, height, imageCanvasData);
pdf.addImage(imageCanvasData, 'JPEG', 0, 0, width, height);
pdf.save('download.pdf');