22

I know similar questions have been asked before but I still can't make it work. I have a div with images inside of it loaded from a bucket in AWS s3, they load perfectly no problem.

Now I want to be able to save as a jpeg whatever is in that specific div (like taking a screenshot), the plugin html2canvas helps with that. The problem is that when I try to actually save it (or simply show immediately the result of such screenshot) I run into these issues:

  • Canvas is tainted => I set allowTaint: true in the plugin but it would throw this error, so I disabled it and the error went away. I keep useCORS set to true though to allow images from another source.

  • Access to image has been blocked by CORS policy

In order to solve this I set up CORS on my AWS S3 bucket, but that didn't seem to work (or it worked partially). I noticed that the response header of those images don't have CORS metadata when the plugin uses them to generate the jpeg. I then tried to set crossOrigin="anonymous" in those images inside the div but it would throw a CORS error right away, which shouldn't happen since the AWS bucket has been set up for that as follows:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

I am running out of options on how to make this work. Any idea on how to proceed from here would be very appreciated.

EDIT: More details, I am using React and the images urls are retrieved from a server. This means that as soon as I get this array of urls I generate:

<div>
  { urls.map(url => <img src={url} alt="some alt" />) }
</div>

If I add the crossOrigin="anonymous" I get the CORS error. If I leave that out, the images display but then the html2canvas plugin throws a CORS error as well when trying to generate the "screenshot".

More details about the HTTP requests. So the first time I load an image inside the div, this is the Response Header:

Accept-Ranges:bytes
Access-Control-Allow-Methods:GET
Access-Control-Allow-Origin:*
Cache-Control:max-age=2592000
Content-Length:508208
Content-Type:image/png
Date:Thu, 16 Feb 2017 18:25:05 GMT
Last-Modified:Wed, 15 Feb 2017 19:09:44 GMT
Server:AmazonS3
Vary:Origin, Access-Control-Request-Headers, Access-Control-Request-Method 

Now this works if crossOrigin='anonymous' and the picture is not from the cache. If the crossOrigin attribute is not set I get:

Accept-Ranges:bytes
Cache-Control:max-age=2592000
Content-Length:508208
Content-Type:image/png
Date:Thu, 16 Feb 2017 19:03:53 GMT
Last-Modified:Wed, 15 Feb 2017 19:09:44 GMT
Server:AmazonS3

or it throws a CORS error on the console without showing any meta data on the response header. I tried adding a random string at the end of the url (?somethingsomething) so that they would never be grabbed from the cache, and that fixed the issue completely. But this is just a hack and it works for now but it is not definitely the solution I am looking for. I think Chrome is doing something with the cache and I have a hard time tracking the source of the issue, other than the fact that it's hard to reproduce this problem on my machine since it always retrieved the screenshot from cache even if I am using completely new images and disable/clear cache. It's very confusing.

G4bri3l
  • 4,996
  • 4
  • 31
  • 53
  • `Access to image has been blocked by CORS policy` - show the code you are using to get the image – Jaromanda X Feb 16 '17 at 01:30
  • You have to either load your image with the `crossOrigin` attribute set to `'anonymous'` directly in your document, or you can try `useCORS` h2c option. `allowTaint` option does just say that you don't care if it taints the canvas or not. – Kaiido Feb 16 '17 at 01:36
  • See the edit, I did try setting the crossOrigin attribute with no luck, and I use `useCORS` set to `true` (forgot to mention that sorry). Still no luck. – G4bri3l Feb 16 '17 at 01:40
  • 1
    Ah so you've got a problem with your bucket's settings. It's been a while but your conf seems ok to me, maybe remove the `Allowed header` field, I think it's not necessary. You can check [this answer](http://stackoverflow.com/questions/35002392/what-do-i-set-cors-settings-to-and-where-so-that-my-canvas-doesnt-get-tainted/35014782), quite old, and I don't have s3 account anymore to test... – Kaiido Feb 16 '17 at 02:04
  • Can you capture and show us the complete request and response headers for a failed request, and the entire CORS error? – Michael - sqlbot Feb 16 '17 at 05:09
  • I updated my question with more info. – G4bri3l Feb 16 '17 at 19:10
  • @Kaiido Thanks for the link, I simplified my CORS settings as suggested there and cleared my cache, it keeps working for me on Chrome, but I tried with other laptops and it doesn't, then I tried a PC and it worked. I'm so lost. – G4bri3l Feb 16 '17 at 19:40
  • It's far late response, but try remove cache for s3. I got similar problem, and just solve with add some random string after url (`?_324`) and it works! – seuling Jul 13 '18 at 09:45
  • I am having the same usecase as yours of generating Screenshot of S3 Image. Unable to find a solution. Seems like issue with Chrome. https://bugs.chromium.org/p/chromium/issues/detail?id=718352 – Rahul Sagore Aug 10 '18 at 11:40
  • @RahulSagore try this https://stackoverflow.com/a/53137836/1815624 for Chrome. – CrandellWS Nov 04 '18 at 04:49
  • The problem is that the image is cached from a former request, without the required CORS headers.Thus, when you ask for it again, for the canvas, with the 'crossorigin' specified, the browser uses the cached version, doesn't see the necessary headers, and raises a CORS error. The solution that worked for me is to add crossorigin="anonymous" to the image tag for the first request. – Adil B Feb 01 '23 at 15:26

5 Answers5

13

See the edit, I did try setting the crossOrigin attribute with no luck, and I use useCORS set to true (forgot to mention that sorry). Still no luck.

I fixed some cors issues I was having with the combination of Google Chrome, AWS S3, and multiple origins.

I found this stackoverflow thread: Chrome + CORS + cache - requesting same file from two different origins

Which links to this bug report: https://bugs.chromium.org/p/chromium/issues/detail?id=260239

Anyhow as workaround solution you can try this modified version of html2canvas: https://gist.github.com/CrandellWS/6bc2078aced496004d7a045e6360f19b

use the options:

allowTaint : false,
useCORS: true

Hope that helps.

FYI, this will add the current time stamp to cors image urls to sidestep a cache issue I was having on Chrome... https://gist.github.com/CrandellWS/6bc2078aced496004d7a045e6360f19b#file-html2canvas-js-L6838

Which means it will effect performance by re-downloading those images...

original post: https://github.com/niklasvh/html2canvas/issues/1544#issuecomment-435640901

CrandellWS
  • 2,708
  • 5
  • 49
  • 111
  • I saw your edits you have added to html2canvas.. it helped to avoid showing blank image after rendering. I can see you have added date.getTime() as a random number at the end of img's src! could you explain why? and is that has a relationship with caching issues? – parse Dec 15 '18 at 21:46
  • @Wowali for me that was mostly for AWS Bucket a way to not use cache version and set it to `anonymous` as was needed for cors to work...to prevent tainting... – CrandellWS Dec 22 '18 at 16:16
  • I posted this on the githubs issues list for the project at https://github.com/niklasvh/html2canvas/issues/1544#issuecomment-435640901 – CrandellWS Dec 24 '18 at 04:46
  • 1
    Yep, it helped me to resolve an issue with CORS with one domain name… thank you so much – parse Dec 26 '18 at 00:10
  • 2
    Does html2pdf has fixed cors version ? or any updated solution please ... Thanks – KcH Nov 12 '20 at 04:24
  • @CrandellWS Hey crandell may i know how can i include the fix as a script tag ? Thanks.. – Sophie Nov 16 '20 at 10:47
  • @Sophie I dont understand what you mean script tag... – CrandellWS Nov 16 '20 at 16:50
  • @CrandellWS I saw the workaround [here](https://gist.github.com/CrandellWS/6bc2078aced496004d7a045e6360f19b#file-html2canvas-js-L6838) but may i know how can i include this in project ? like a CDN script tag ... hope its clear – Sophie Nov 17 '20 at 04:21
  • just download it and server it on your system there is no CDN just this one off fix as a gist – CrandellWS Nov 17 '20 at 15:21
3

I solved this problem by adding proxy:( image src ) option in html2canvas. Now your image is also included in pdf

Typescript Code:

download() {
        var data = document.getElementById('view-eob');
        html2canvas(data, { proxy: this.eobDetail.member.parentCompany.logo })
        .then(canvas => {
            var imgWidth = 208;
            var imgHeight = canvas.height * imgWidth / canvas.width;
            const contentDataURL = canvas.toDataURL('image/png')
            let pdf = new jsPDF('p', 'mm', 'a4');
            var position = 0;
            pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
            pdf.save(`${this.eobDetail.episode.name}-EOB.pdf`);
        });
    }

HTML Code:

<div>
     <img [src]="this.eobDetail.member.parentCompany.logo"/>
</div>
<button type="button" (click)="download()"> Download</button>
Shahid Manzoor Bhat
  • 1,307
  • 1
  • 13
  • 32
2

I solved this error with adding crossOrigin attribute at IMG tag. So, your code will look like (tag at React js):

<Image crossOrigin="true" />

And my configuration at S3 bucket with CORS:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>http://localhost:8000</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
<CORSRule>
    <AllowedOrigin>https://testing.d1wr8lk28mi6l0.amplifyapp.com</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

HTML2CANVAS:

 html2canvas(getWrapper, { allowTaint: true, useCORS: true, logging: true })
  .then((canvas) => {
    const imgData = canvas.toDataURL('image/png');
    console.log(imgData);
  });
1

We solved this problem by changing the Response headers policy in the CloudFront distribution that sits in front of our S3 bucket.

Previously we had it set to SimpleCORs, which was responding with the error: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Changing it to CORS-With-Preflight fixed the issue.

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-managed-response-headers-policies.html#managed-response-headers-policies-cors-preflight

Kevin Collins
  • 1,453
  • 1
  • 10
  • 16
0

I tried the allowTaint/useCORS solution but the problem I ran into is Chromium will cache the image after the first load, but not preserve the CORS headers, resulting in no image rendered.

The only solution that worked for me was to load the image server-side and base64-encode it into a string that I sent to the client side to use in an image tag.

For node, this is what that looks like:

import fetch from 'node-fetch'
const response  = await fetch(url);
image_base64 = (await response.buffer()).toString('base64');

with the resulting image tag on the other end as:

<img src=`data:image/jpeg;base64, ${image_base64}` />

Your mimetype may vary; I would write a function to determine that based on the extention.

Dave Cole
  • 2,446
  • 2
  • 20
  • 26