php-chrome-html2pdf icon indicating copy to clipboard operation
php-chrome-html2pdf copied to clipboard

No images/css/assets on relative urls

Open Baltazar5000 opened this issue 2 years ago • 3 comments

Hello.

Debian. No images/css/assets on relative urls. /css/style.css, /image.jpg - not working, I need to specify full site url https://site.com/css/style.css Google from example is not working too.

Is here anyway to auto-detect current domain for relative urls? Or may be option {"site":"https://site.com"}? Thank you!

Baltazar5000 avatar Sep 25 '23 14:09 Baltazar5000

Technically relative URLs should work fine, I used them in most of my projects. Can you try to use a base URL in HTML?

<base href="http://www.example.com/">

spiritix avatar Sep 25 '23 14:09 spiritix

With base all works well. But base is not compatible with many sites. May be need option {"add_base": true}?

  await page.evaluate(() => {
    const base = document.createElement('base');
    base.href = window.location.origin;

    document.head.insertBefore(base, document.head.firstChild);
  });

P.s. Tried in Converted.js on 84 line - doesn't work (window.location.origin is null) P.p.s: It is safe? (Is it looking for local files?)

Baltazar5000 avatar Sep 25 '23 16:09 Baltazar5000

Other way:

    addBaseTag(htmlString, baseURL) {
        const baseTag = '<base href="'+baseURL+'">';
        
        if (htmlString.includes('<base ')) {
            return htmlString;
        }
    
        const headOpeningTagIndex = htmlString.indexOf('<head>');
    
        if (headOpeningTagIndex === -1) {
            return htmlString;
        }
    
        const positionToInsert = headOpeningTagIndex + '<head>'.length;
    
        return htmlString.slice(0, positionToInsert) + baseTag + htmlString.slice(positionToInsert);
    }
      if (options.hasOwnProperty('baseUrl')) {
          this.html = this.addBaseTag(this.html, options.baseUrl)
      }

Or maybe it's better to not use $content = file_get_contents($url); and open the page in a browser?

Baltazar5000 avatar Sep 25 '23 18:09 Baltazar5000